实体框架代码优先:POCO的继承

时间:2013-05-08 00:44:29

标签: entity-framework code-first poco

首先在实体框架代码中定义一些POCO对象(实体)时遇到问题4.我有一个主实体,假设Entity_A只有一个属性,只有ID(主键)。其余实体(本例中为Entity_B)继承自它(childs),但其中一些(Entity_C)继承自另一个实体(来自Entity_B,而不是来自Entity_A)。例如:

public class Entity_A
{
  public virtual Guid ID { get; set; }
}

// Entity_B has not primary key defined within as it inherits from Entity_A
public class Entity_B : Entity_A
{
  public virtual string propertyB1 { get; set; }
  public virtual string propertyB2 { get; set; }
  public virtual string propertyB3 { get; set; }
}

// Entity_C has not primary key defined within as it inherits from Entity_A through Entity_B
public class Entity_C : Entity_B
{
  public virtual string propertyC1 { get; set; }
  public virtual string propertyC2 { get; set; }
  public virtual string propertyC3 { get; set; }
}

所以在执行之后,Entity_A,Entity_B,Entity_C的表会自动生成,但只有Entity_A和Entity_B的表是正确的,但不是Entity_C的表:

表Entity_A包含字段:
    -ID

这是正确的。

表Entity_B包含字段:
    -ID
    -propertyB1
    -propertyB2
    -propertyB3

也是正确的。

表Entity_C有字段:
    -ID
    -propertyC1
    -propertyC2
    -propertyC3

对我来说不正确,对于Entity_C我期望以下字段:
    -ID
    -propertyB1
    -propertyB2
    -propertyB3
    -propertyC1
    -propertyC2
    -propertyC3

我做错了什么?首先是实体框架代码(版本4.1)是否支持继承?

提前致谢。

1 个答案:

答案 0 :(得分:1)

尝试向Entity_C添加记录,您会注意到记录也会添加到Entity_B和Entity_A。

这是表继承。 Entity_C是Entity_B,为什么要复制行?