实体框架中同一张表上的一对多关系

发布于 2024-10-08 11:06:49 字数 310 浏览 0 评论 0原文

我有两个表,其中一个用户可以有多个联系人:

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

假设我想通过 Userid 从用户表中的 UserNames 中获取所有 ContactNames。

注意Contact表在当前数据上下文中是看不到的,已经变成了多对多关系

如何查询?

如果需要插入或删除怎么办?

我尝试了“包含”方法,但它不起作用。您有什么建议吗?

非常感谢。

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.

Note that the Contact table cannot be seen in the current data context, it has been turned into a many to many relationship

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九公里浅绿 2024-10-15 11:06:49
var id = 1; // id to find
context.Users
     .Where(x=>x.UserId = id)
     .SelectMany(x=>x.Users)
     .Select(x=>x.UserName)
     .ToArray();

alt text

从数据库生成后,您的模型有 2 个子集合:Users 和 Users1。

  1. 其中之一对应于用户,即当前用户的联系人。
  2. 另一个存储用户,当前用户是其联系人。

您可以通过编辑器将它们重命名为代表其对 Contacts 和 ContactsFor 的含义。

alt text

如果您仍然想有 2 种类型而不是 Type+(Many-To-Many Ref),那么在编辑器中您可以删除引用、创建新实体联系人、设置所有映射、添加引用。完成所有这些后 - 您将拥有如下所示的模型:
alt text

要实现此目的:

  1. 删除多对多引用
  2. Crete 新实体 Contact
  3. 添加属性ContactId 和 UserId,将 StoreGeneratePattern 设置为 none
  4. 添加 Contact 的映射
  5. 添加 Contacts 和 ContactFor 的关联

但这并不那么容易。

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

alt text

After generation from db your model has 2 sub-collections: Users and 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.

alt text

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. After all this is done - you will have model look like this:
alt text

To Achieve this:

  1. Delete Many-To-Many reference
  2. Crete new Entity Contact
  3. Add properties ContactId and UserId, set StoreGeneratedPattern to none
  4. Add mappings for Contact
  5. Add associations for Contacts and ContactFor

But it's not that easy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文