【发布时间】:2015-01-26 13:12:03
【问题描述】:
我使用的是 EF6 Code First,这是一个重现我的问题的简单模型:
abstract class GeoInfo
{
public int Id { get; set; }
public double CoordX { get; set; }
public double CoordY { get; set; }
}
class PersonGeoInfo : GeoInfo
{
[Required]
public Person Person { get; set; }
}
class CarGeoInfo : GeoInfo
{
[Required]
public Car Car { get; set; }
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
public virtual PersonGeoInfo PersonGeoInfo { get; set; }
}
class Car
{
public int Id { get; set; }
public string Number { get; set; }
public virtual CarGeoInfo CarGeoInfo { get; set; }
}
还有一个上下文:
class MyContext : DbContext
{
public DbSet<GeoInfo> GeoInfos { get; set; }
public DbSet<PersonGeoInfo> PersonGeoInfos { get; set; }
public DbSet<CarGeoInfo> CarGeoInfos { get; set; }
public DbSet<Person> Persons { get; set; }
public DbSet<Car> Cars { get; set; }
}
Entity Framework 生成这个数据库:
查看GeoInfoes 外键约束。他们都在一个列中,使用这个数据库是不可能的。但是 EF 并没有警告我,它只是抛出了数据库异常:The INSERT statement conflicted with the FOREIGN KEY...
我尝试使用 TPT 策略 - 同样的问题,但混合是在关联键和继承键之间。
我尝试在模型中明确定义外键 - 没有帮助。没有什么能阻止 EF 在同一 PK 列中生成 FK 约束。
我无法为Car 和Person 创建基类,因为在实际应用中它们已经参与了另一个层次结构。
我是否使用了错误的实体框架,或者它真的无法将一对一的关系与继承一起映射到数据库?
【问题讨论】:
-
您需要
CarGeoInfo和PersonGeoInfo做什么?PK, FK是因为一对一的关系。如果您想拥有单独的键,请从您的models中删除virtual属性,这将在GeoInfo表中生成FK列。 -
@Ghukas 不,不会
-
为什么 TPT 策略不适应您的场景?
-
是的,它会的,我使用了您示例中的类,没有
virtual属性。 EF 已为Cars和People实体生成外键。我正在使用 EF 6.1.2 -
@Ghukas 很奇怪,我也刚试过。您能否提供完整的示例代码作为答案?
标签: c# entity-framework inheritance ef-code-first one-to-one