本文介绍了实体框架6& TPH继承:默认情况下,将具有相同名称的属性映射到同一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 公共类MyContext:DbContext 
{
public DbSet< Device>设备{get;组;

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 基类的一部分 - 它是实现接口合同实现的派生类的属性。



有可能使这是默认行为,而不是为每个派生类添加一个新的映射?

解决方案

使用(可从EF6起),将其排除

$ b

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//您的代码在$ b $之前b modelBuilder.Properties()。配置(prop => prop.HasColumnName(prop.ClrPropertyInfo.Name));
//你的代码在
之后

这个映射具有相同名称的属性在不同的派生类型到同一个表列,没有明确的调用,如问题中提到的那样。


As of EF6 it is possible to do something like this when configuring Entity mappings using Table Per Hierarchy inheritance:

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 is not part of the Device base class- it is a property of the derived classes implemented to fulfill an interface contract.

Is it possible to make this the default behavior as opposed to having to add a new mapping for each derived class?

解决方案

Used Custom Code First Conventions, which are available from EF6 onwards, to sort this out:

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

This maps properties with the same name in different derived types to the same table column without explicit calls like those mentioned in the question.

这篇关于实体框架6&amp; TPH继承:默认情况下,将具有相同名称的属性映射到同一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 00:18