简体   繁体   中英

Generic entity configuration class in EF Core 2

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM