实体框架4多到多更新 [英] entity framework 4 many to many update
问题描述
我有3个表 -
User (Id, Name)
Roles (Id, Name)
UserRoles (UserId, RoleId)
我认为这是自我解释。如何更新UserRoles中的条目(UserId和RoleId)?
I think they are self explanatory. How do I update an entry (UserId and RoleId) in UserRoles?
context.User.Roles
给我角色列表,但如何更新?
context.User.Roles
gives me the list of roles but how do I update them?
谢谢。
推荐答案
从您的评论:
context.User.Roles给我列出
的角色。我可以做一个for-each和
更新Id,但是如何更新
对应的UserId foreach RoleId在
表中?
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?
首先,你不应该更新Id的。
其次,由于你使用EF,你应该尝试用对象(或实体)而不是DB-many-to-many-mapping-tables。每个用户
实体具有角色
的集合。如果您从 User.Roles
集合中删除角色
,并调用 context.SaveChanges()
,相应的条目将从 UserRoles
tabele中删除。类似地,当您向 User.Roles
集合添加角色
对象并保存更改时,新条目将在 UserRoles
表中创建。
以下示例可能对于清楚起见有用:
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).
这篇关于实体框架4多到多更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!