views:

51

answers:

1

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.

A: 

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

Yakimych
Thank you for your answer. I learnt that I have to delete the record completely from the join table and add a new one instead of trying to update the existing record. Also, I needed to have the UserId and RoleId as a composite key in the join table for this to work.

related questions