ASP.NET MVC: how can I change the user role?

In my application, I have the administrator role, and these users can change the role of the user (client, manager ...). I use the built-in membership provider. Here is what I tried to do ...

[AcceptVerbs(HttpVerbs.Post)] public ActionResult EditRole(string usernameID, FormCollection formValues) { var db = new AppDataContext(); var user = db.Users.SingleOrDefault(d => d.UserName == usernameID); string choosenRole = Request.Form["Roles"]; var tuple = db.UsersInRoles.SingleOrDefault(d => d.UserId == user.UserId); var roleNameID = db.Roles.SingleOrDefault(d => d.RoleName == choosenRole).RoleId; tuple.RoleId = roleNameID; db.SubmitChanges(); return RedirectToAction("Index"); } 

But I got this error.

The value of the member 'RoleId' of an object of type 'UsersInRole' has been changed. The member defining the identity of an object cannot be changed. Consider adding a new object with a new identifier and deleting an existing one.

I am stuck. Any ideas?

+6
c # asp.net-mvc
source share
2 answers

Instead of trying to access membership tables directly from db (datacontext), you should use the static User , Roles and Membership classes provided in your action code.

Like this:

 System.Web.Security.Roles.AddUserToRole(usernameID, choosenRole); 

Assuming your usernameID is the string key of the user you want to change, and choosenRole contains the key of the role name that you want to add to the user:

 [AcceptVerbs(HttpVerbs.Post)] public ActionResult EditRole(string usernameID, FormCollection formValues) { string choosenRole = Request.Form["Roles"]; System.Web.Security.Roles.AddUserToRole(usernameID, choosenRole); return RedirectToAction("Index"); } 
+9
source share

UsersInRole.RoleId is part of the primary key of the UsersInRole table and therefore cannot be changed. You must follow the suggestion given by the error message and delete the existing instance of UsersInRole and create a new one.

0
source share

All Articles