简体   繁体   中英

Entity Framework Core: General model configuration

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

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");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM