使用 EF4 Code First 具有 2 个相同类型的属性/关系时出错
我有一个与 Y 具有多对多关系的类 X。如果我只有该属性,那么 EF 将正确生成第三个 XY 表。但是,如果我想要与类型 X 建立多对多关系,并且与 Y 建立一对多关系。
为了说明这一点,我有这样的事情:
class Location
{
public ICollection<Person> Visitors {get;set;}
}
class Person
{
public Location Home {get;set}
public ICollection<Location> VisitedPlaces {get;set;}
}
当我有两个引用时,EF 停止生成第三个表,只给我每个属性都是 1 对 1 的关系!
I have a class X that has a many to many relationship with Y. If I only have that property then EF will correctly produce the 3rd XY table. However if I want to have that many to many relationship to type X AND also have a 1 to many relationship to Y.
To illustrate say I have something like this:
class Location
{
public ICollection<Person> Visitors {get;set;}
}
class Person
{
public Location Home {get;set}
public ICollection<Location> VisitedPlaces {get;set;}
}
When I have both references, EF stops genereting the 3rd table and only gives me a 1 to 1 relationship for each property!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须将其添加到派生上下文中:
问题是 EF 无法正确推断映射,因为它不知道
Location
类中的Visitors
集合是否是其中的一部分声明的多对多关系或一对多关系(它不能是两者的一部分)。我的示例定义一对多关系在Location
上没有导航属性,因此 EF 现在知道它是多对多关系的一部分。You must add this to your derived context:
The problem is that EF is not able to infer correctly the mapping because it doesn't know if
Visitors
collection inLocation
class is part of declared many-to-many relation or one-to-many relation (it can't be part of both). My example defines that one-to-many relation doesn't have navigation property onLocation
so EF now knows that it is part of many-to-many relation.