Generic entity configuration class in EF Core 2

c# ef-core-2.0 entity-framework-core

Question

I'm trying to create a generic configuration class for my entities but i'm stuck.

I have an abstract class called EntityBase:

public abstract class EntityBase
{
    public int Id { get; set; }
    public int TenantId { get; set; }
    public DateTime CreatedOn { get; set; }
    public DateTime UpdatedOn { get; set; }
}

And many other classes that inherit from EntityBase, in which i have to configure the DateTime properties in each one with the same code. This way:

void EntityTypeConfiguration<MyEntity>.Configure(EntityTypeBuilder<MyEntity> builder)
    {
        builder.HasIndex(e => e.TenantId);
        builder.Property(e => e.CreatedOn)
              .ValueGeneratedOnAdd()
              .HasDefaultValueSql("GETDATE()");

        // Other specific configurations here
    }

I would like to be able to call somthing like: builder.ConfigureBase() and avoid the code duplication. Any ideas?

1
3
12/21/2017 6:17:57 PM

Accepted Answer

There are several way you can accomplish the goal. For instance, since you seem to be using IEntityTypeConfiguration<TEntity> classes, you could create a base generic configuration class with virtual void Configure method and let your concrete configuration classes inherit from it, override the Configure method and call base.Configure before doing their specific adjustments.

But let say you want to be able to exactly call builder.ConfigureBase(). To allow that syntax, you can simply move the common code to a custom generic extension method like this:

public static class EntityBaseConfiguration
{
    public static void ConfigureBase<TEntity>(this EntityTypeBuilder<TEntity> builder)
        where TEntity : EntityBase
    {
        builder.HasIndex(e => e.TenantId);
        builder.Property(e => e.CreatedOn)
              .ValueGeneratedOnAdd()
              .HasDefaultValueSql("GETDATE()");

    }
}

with sample usage:

void IEntityTypeConfiguration<MyEntity>.Configure(EntityTypeBuilder<MyEntity> builder)
{
    builder.ConfigureBase();
    // Other specific configurations here
}
4
12/21/2017 6:50:48 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow