【发布时间】:2018-05-15 06:15:09
【问题描述】:
我有两个表,我想创建从 User 到 Contact 的 1-n 关系并在 EF 中反转。这意味着我需要与 2 个目的地的 2 路关系,它们也是基表。
用户类中的Contact 表应该作为ICollection 引入,所以我的关系出错了,它们都是一边。check this picture 但是如果我删除ICollection,一切都是正确的。
我应该如何解决这个问题?
public class User
{
[Key]
public Guid Id {get; set;}
[ForeignKey("ContactId")]
public virtual ICollection<Contact> Contacts {get; set;}
public Guid? ContactId {get;set;}
}
public class Contact
{
[Key]
public Guid Id {get; set;}
[ForeignKey("UserId")]
public virtual User User {get; set;}
public Guid? UserId {get; set;}
}
如果我删除联系人check this picture 的外键:
我想要这些表之间的更多关系,但方向不同。 check this picture
【问题讨论】:
-
删除
public Guid? ContactId {get;set;}和[ForeignKey("ContactId")]。您想要User与Contact的 1-n 关系,因此应将Contact定义为集合;即public virtual ICollection<Contact> Contacts {get; set;} -
谢谢...我在您写的时候进行了测试...但我有一个从 "contact" 到 "user" 的 1-n 关系。我也需要与反向方向的更多关系。从“用户”到“联系人”
-
为什么(你认为)你需要这种额外的关系?你会如何使用它?
-
让我举个例子:我的用户表是给我老板的,联系表是给他的员工的,所以每个老板都可以有多名员工......所以在联系表中应该插入用户 ID,这意味着谁是你的老板?然后我想要老板 1 的一个联系人的名字也有另一个条件(对于与用户表有关系的其他表)所以我应该在我的用户表中有联系人 ID 和虚拟来从中获取数据。我希望我解释清楚。
-
再次,您将如何使用它?使用更多的 C#(也许还有 SQL)来解决你的问题。
标签: c# entity-framework entity icollection