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!
Category: Software
Tags: Entity Framework Libraries