【问题标题】:Entity Framework 6 & TPH inheritance: Map properties with the same name to same column by defaultEntity Framework 6 & TPH 继承:默认将同名属性映射到同一列
【发布时间】:2013-10-24 21:56:30
【问题描述】:

从 EF6 开始,可以在使用 Table Per Hierarchy 继承配置实体映射时执行以下操作:

public class MyContext : DbContext 
{
    public DbSet<Device> Devices { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ABatteryPoweredDevice>().Property(c => c.BatteryLevel).HasColumnName("BatteryLevel");
        modelBuilder.Entity<ADifferentBatteryPoweredDevice>().Property(c => c.BatteryLevel).HasColumnName("BatteryLevel");
    }
}

BatteryLevel 不是Device 基类的一部分,它是实现接口契约的派生类的属性。

是否可以将此作为默认行为,而不是必须为每个派生类添加新映射?

【问题讨论】:

    标签: .net entity-framework-6 table-per-hierarchy


    【解决方案1】:

    使用Custom Code First Conventions(从 EF6 开始提供)来解决这个问题:

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //your code before
            modelBuilder.Properties().Configure(prop => prop.HasColumnName(prop.ClrPropertyInfo.Name));
            //your code after
        }
    

    这会将不同派生类型中具有相同名称的属性映射到同一个表列,而无需像问题中提到的那样显式调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 2017-12-31
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      相关资源
      最近更新 更多