tempid
tempid

Reputation: 8228

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 but how do I update them?

Thank you.

Upvotes: 4

Views: 6302

Answers (1)

Yakimych
Yakimych

Reputation: 17762

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

Upvotes: 6

Related Questions