1

When configuring my model mappings in EF Core, I want to set some general mapping rules, eg. tell every class having Id property that this property gets mapped to DB column ID.

Using Entity Framework, I was able to achieve this using this code:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Types<IEntity<long>>().Configure(c =>
    {
        c.Property(x => x.Id).HasColumnName("ID");
    });
}

(IEntity<long> is a simple interface having only single property long Id { get; set; }. Every entity class in my model simply implements this interface.)

Is anything similar possible also with Entity Framework Core 2.2+?

Jan Palas
  • 1,865
  • 1
  • 23
  • 35

1 Answers1

0

In the end, I ended up with this solution:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (IMutableEntityType mutableEntityType in modelBuilder.Model.GetEntityTypes())
    {
        bool isEntity = mutableEntityType.ClrType.GetInterface($"{nameof(IEntity<int>)}`1") != null;
        if (isEntity)
        {
            modelBuilder.Entity(mutableEntityType.ClrType).Property(nameof(IEntity<int>.Id)).HasColumnName("ID");
        }
    }
}
Jan Palas
  • 1,865
  • 1
  • 23
  • 35