Blog

Filter posts by the Tags of Blog section!

Base class Model builder in EF core by taking the advantage of IEntityTypeConfiguration Saturday, 15 May 2021

In order to generalize a mapping class of entity framework core, there is an interface with the following definition:

 

  public interface IEntityTypeConfiguration<TEntity> where TEntity : class

    {

        //

        // Summary:

        //     Configures the entity of type TEntity.

        //

        // Parameters:

        //   builder:

        //     The builder to be used to configure the entity type.

        void Configure(EntityTypeBuilder<TEntity> builder);

    }


 

It takes the EntityTypeBuilder as a generic parameter, so we can use it to generalize our base classes in EF core. Assume the following chile-parent classes:

 

class BaseClass

{

    public DateTime Id { get; set; }

}



class AClass : BaseClass

{

    public int Prop1 { get; set; }

}


 

By using the IEntityTyoeConfiguration interface we can implement a base mapping class like below: 


 

 abstract class BaseModelBuilder<TModel> : IEntityTypeConfiguration<TModel> where TModel : BaseClass

{

    public virtual void Configure(EntityTypeBuilder<TModel> entityTypeBuilder)

    {

        entityTypeBuilder.HasKey(b => b.Id);

    }

}

 

And passes our derived class model builder to it: 


 

class AClassModelBuilder : BaseModelBuilder<AClass>

{

    public override void Configure(EntityTypeBuilder<AClass> builder)

    {

        builder.ToTable("AClass");

        builder.HasKey(b => b.Prop1);

        base.Configure(builder);

    }

}

 

I remember the earlier versions of EF core that didn’t contain this interface!

 

comments powered by Disqus