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