Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 554
alecardv Avatar asked Sep 03 '25 04:09

alecardv


1 Answers

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
}
like image 128
Ivan Stoev Avatar answered Sep 06 '25 00:09

Ivan Stoev