【问题标题】:Entity Framework Inheritance Mapping (TPH)实体框架继承映射 (TPH)
【发布时间】:2014-06-27 03:55:03
【问题描述】:

我正在将一个项目从 nHibernate 转换为 Entity Framework,但在映射继承时遇到了映射问题。

我有以下基类(为简洁起见):

public abstract class Status
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class ProjectStatus : Status
{ 

}

public class TaskStatus : Status 
{

}

有人能指出正确的方向吗?如何编写TaskStatusProjectStatus 的映射以从Status 继承?我想使用每个层次结构的表(所有使用鉴别器保存在一个表中)

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    每个层次结构的表是默认设置。除了已有的设置之外,您不需要提供任何其他设置。

    这取自weblogs.asp.net的TPH示例:

    public abstract class BillingDetail 
    {
        public int BillingDetailId { get; set; }
        public string Owner { get; set; }        
        public string Number { get; set; }
    }
    
    public class BankAccount : BillingDetail
    {
        public string BankName { get; set; }
        public string Swift { get; set; }
    }
    
    public class CreditCard : BillingDetail
    {
        public int CardType { get; set; }                
        public string ExpiryMonth { get; set; }
        public string ExpiryYear { get; set; }
    }
    
    public class InheritanceMappingContext : DbContext
    {
        public DbSet<BillingDetail> BillingDetails { get; set; }
    }
    

    这将创建一个名为 BillingDetails 的表,其中包含一个鉴别器列。

    鉴别器列

    正如您在上面的 DB 架构中看到的,Code First 必须添加一个特殊的 区分持久类的列:鉴别器。 这不是我们对象模型中持久类的属性; 它由 EF Code First 内部使用。默认情况下,列名是 “判别器”,其类型为字符串。这些值默认为 持久类名——在本例中为“BankAccount”或“CreditCard”。 EF Code First 自动设置和检索鉴别器 价值观。

    【讨论】:

    • 谢谢!这帮助很大!
    猜你喜欢
    • 2015-10-24
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    相关资源
    最近更新 更多