实体框架4多对多更新

发布于 2024-09-16 22:35:27 字数 232 浏览 1 评论 0原文

我有 3 个表 -

User (Id, Name)
Roles (Id, Name)
UserRoles (UserId, RoleId)

我认为它们是不言自明的。如何更新 UserRoles 中的条目(UserId 和 RoleId)?

context.User.Roles 为我提供了角色列表,但如何更新它们?

谢谢。

I have 3 tables -

User (Id, Name)
Roles (Id, Name)
UserRoles (UserId, RoleId)

I think they are self explanatory. How do I update an entry (UserId and RoleId) in UserRoles?

context.User.Roles gives me the list of roles but how do I update them?

Thank you.

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

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

发布评论

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

评论(1

寂寞美少年 2024-09-23 22:35:27

从你的评论来看:

context.User.Roles 给了我列表
的角色。我可以做一个 for-each 和
更新Id,但是如何更新
foreach RoleId 中对应的 UserId
那张桌子?

首先,您不应该更新 ID。
其次,由于您使用的是 EF,因此您应该尝试从对象(或实体)角度思考,而不是“DB 多对多映射表”。每个User实体都有一个Roles集合。如果您从 User.Roles 集合中删除一个 Role 并调用 context.SaveChanges(),相应的条目将从 User.Roles 集合中删除>用户角色 表。同样,当您将 Role 对象添加到 User.Roles 集合并保存更改时,将在 UserRoles 表中创建一个新条目.
为了清楚起见,以下示例可能有用:(

var user = context.Users.Include("Roles").Where(u => u.Name == "User1").FirstOrDefault();
user.Roles.Remove(user.Roles.Where(r => r.Name == "Admin").FirstOrDefault());
context.SaveChanges();

为简单起见,省略了空引用检查)。

From your comment:

context.User.Roles gives me the list
of roles. I can do a for-each and
update the Id, but how do I update the
corresponding UserId foreach RoleId in
that table?

First of all, you should NOT update the Id's.
Secondly, since you are using EF, you should try to think in terms of objects (or entities), rather than "DB-many-to-many-mapping-tables". Every User entity has a collection of Roles. If you remove a Role from the User.Roles collection and call context.SaveChanges(), the corresponding entry will be deleted from the UserRoles tabele. Similarly, when you add a Role object to the User.Roles collection, and save changes, a new entry will be created in the UserRoles table.
The following sample might be useful for clarity:

var user = context.Users.Include("Roles").Where(u => u.Name == "User1").FirstOrDefault();
user.Roles.Remove(user.Roles.Where(r => r.Name == "Admin").FirstOrDefault());
context.SaveChanges();

(null-reference checks omitted for simplicity).

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