实体框架4多对多更新
我有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从你的评论来看:
首先,您不应该更新 ID。
其次,由于您使用的是 EF,因此您应该尝试从对象(或实体)角度思考,而不是“DB 多对多映射表”。每个
User
实体都有一个Roles
集合。如果您从User.Roles
集合中删除一个Role
并调用context.SaveChanges()
,相应的条目将从User.Roles
集合中删除>用户角色 表。同样,当您将Role
对象添加到User.Roles
集合并保存更改时,将在UserRoles
表中创建一个新条目.为了清楚起见,以下示例可能有用:(
为简单起见,省略了空引用检查)。
From your comment:
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 ofRoles
. If you remove aRole
from theUser.Roles
collection and callcontext.SaveChanges()
, the corresponding entry will be deleted from theUserRoles
tabele. Similarly, when you add aRole
object to theUser.Roles
collection, and save changes, a new entry will be created in theUserRoles
table.The following sample might be useful for clarity:
(null-reference checks omitted for simplicity).