在我的应用程序中,我有一个管理员角色,这些类型的用户可以更改用户(客户端,经理……)的角色.我正在使用内置的会员提供商.这是我试图做的……
[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"); }
但是,我收到了这个错误..
Value of member ‘RoleId’ of an object of type ‘UsersInRole’ changed.
A member defining the identity of the object cannot be changed.
Consider adding a new object with new identity and deleting the existing one instead.
我被困了.有任何想法吗?
解决方法
您可以使用操作代码中提供的User,Roles和Membership静态类,而不是尝试直接从db(datacontext)访问成员资格表.
像这样:
System.Web.Security.Roles.AddUserToRole(usernameID,choosenRole);
假设您的usernameID是您要更改的用户的字符串键,并且choosenRole包含您要将用户添加到的角色名称键:
[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"); }