EF代码优先:非规范化继承类型

时间:2011-06-22 16:50:12

标签: c# entity-framework entity-framework-4.1 ef-code-first code-first

我有以下实体:

Human

-Name

-Age

-Height

-Weight
SuperHuman : Human

-SuperPower

EF正在创建仅具有Power属性的SuperHumans表,并且在查询时连接到Humans表。我想要SuperHumans桌上的所有栏目。

可以配置EF 4.1 Code First来执行此操作吗?

3 个答案:

答案 0 :(得分:1)

不会让人类局部工作?如果这不起作用,只需查看Table-Per-Hierarchy vs Table-Per-Type vs Table-Per-Concrete-Type(TPH,TPT,TPC)。您目前正在使用TPT而您想要TPC。

答案 1 :(得分:0)

这样做的一种方法是使关系成为Has-a关系而不是Is-a关系。

public class SuperHuman
{
    public Human TheHuman { get; set; }
    public string SuperPower { get; set; }
}

生成的数据库表应包含Human和SuperHuman的所有字段(只要您没有单独的Human表,在这种情况下将创建单独的Human表,并将外键添加到链接桌子在一起。)

它的实用性有限,因为它打破了继承。您可能会找到更好的解决方案。


编辑:您可以这样做:

public class SuperHuman : Human
{
    public string Name 
    { 
        get { return base.Name; } 
        set { base.Name = value; } 
    }
}

注意:这未经过测试,可能不是最佳解决方案。我把它作为一种可能的解决方案包括在内。

答案 2 :(得分:0)

我只需配置SuperHuman来映射继承的属性,如下所示:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<SuperHuman>().Map(m => m.MapInheritedProperties());
    {