开发者

entity framework 4 many to many update

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 bu开发者_Python百科t how do I update them?

Thank you.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜