简体   繁体   English

同一个表中的Entity Framework中的一对多关系

[英]one to many relationship in Entity Framework on the same table

I have two tables, in which one user can have several contacts: 我有两个表,其中一个用户可以有几个联系人:

User(UserId, UserName)
Contact(UserId, ContactId)

Suppose I would like to get all the ContactNames from the UserNames in the User Table by the Userid. 假设我想通过Userid从User Table中的UserNames获取所有ContactNames。

Note that the Contact table cannot be seen in the current data context, it has been turned into a many to many relationship 请注意,在当前数据上下文中无法看到Contact表,它已经变成了多对多的关系

How can I do the query? 我该如何查询?

What If I need to insert or delete? 如果我需要插入或删除该怎么办?

I tried the "include" method but it does not work. 我尝试了“包含”方法,但它不起作用。 Do you have any suggestions? 你有什么建议吗?

Thank you very much. 非常感谢你。

var id = 1; // id to find
context.Users
     .Where(x=>x.UserId = id)
     .SelectMany(x=>x.Users)
     .Select(x=>x.UserName)
     .ToArray();

替代文字

After generation from db your model has 2 sub-collections: Users and Users1. 从db生成后,您的模型具有2个子集合:Users和Users1。

  1. One of it corresponds to users, that are contacts for current user. 其中之一对应于用户,即当前用户的联系人。
  2. Another stores users, that current user is contact for. 另一个存储用户,当前用户是联系人。

You can rename them to represent their meaning to Contacts and ContactsFor via editor. 您可以通过编辑器重命名它们,以将其含义表示为Contacts和ContactsFor。

替代文字

If you still want to have 2 types instead of Type+(Many-To-Many Ref), then in editor you can delete reference, create new entity Contact, setup all mapping, add references. 如果您仍然希望有2种类型而不是Type +(多对多参考),那么在编辑器中您可以删除引用,创建新实体联系人,设置所有映射,添加引用。 After all this is done - you will have model look like this: 完成所有这些后 - 您将看到如下模型: 替代文字

To Achieve this: 为达到这个:

  1. Delete Many-To-Many reference 删除多对多参考
  2. Crete new Entity Contact 克里特岛新的实体Contact
  3. Add properties ContactId and UserId, set StoreGeneratedPattern to none 添加属性ContactId和UserId,将StoreGeneratedPattern设置为none
  4. Add mappings for Contact 添加Contact映射
  5. Add associations for Contacts and ContactFor 添加Contacts和ContactFor的关联

But it's not that easy. 但这并不容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM