实体框架继承映射(TPH) [英] Entity Framework Inheritance Mapping (TPH)

查看:80
本文介绍了实体框架继承映射(TPH)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将项目从nHibernate转换为实体框架,并坚持映射一个继承的映射问题。

I'm working on converting a project from nHibernate to Entity Framework and stuck on a mapping issue with mapping an inheritance.

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

I have the following base class (shortened for brevity):

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

public class ProjectStatus : Status
{ 

}

public class TaskStatus : Status 
{

}

有人可以指出正确的方向,写入 TaskStatus ProjectStatus 的映射继承自状态 ?我想使用每层次表(所有这些都使用Discriminator保存在一个表中)

Can someone point me in the right direction for how to write the mappings for TaskStatus and ProjectStatus to inherit from Status? I would like to use table-per-hierarchy (all saved in one table using a Discriminator)

推荐答案

表层次结构是默认。您不应该需要提供除了您已经拥有的任何其他设置。

Table Per Hierarchy is the default. You shouldn't need to provide any additional setup besides what you already have.

这是从 weblogs.asp.net

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的单个表,带有一个discriminator列。 p>

This will create a single table called BillingDetails with a discriminator column.


鉴别器列

Discriminator Column

如上面的DB模式所示,Code First添加一个特殊的
列来区分持久化类:鉴别器。
这不是我们对象模型中持久化类的属性;
它由EF Code First内部使用。默认情况下,列名称为
鉴别符,其类型为字符串。该值默认为
持久化类名称 - 在这种情况下为BankAccount或CreditCard。
EF代码首先自动设置和检索鉴别器
值。

As you can see in the DB schema above, Code First has to add a special column to distinguish between persistent classes: the discriminator. This isn’t a property of the persistent class in our object model; it’s used internally by EF Code First. By default, the column name is "Discriminator", and its type is string. The values defaults to the persistent class names —in this case, "BankAccount" or "CreditCard". EF Code First automatically sets and retrieves the discriminator values.

这篇关于实体框架继承映射(TPH)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆