Entity Framework Core: General model configuration

.net c# ef-core-2.2 entity-framework-core

Question

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+?

1
1
12/11/2018 10:10:00 AM

Accepted Answer

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");
        }
    }
}
0
12/12/2018 6:37:42 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow