I have been trying to update a user record from within the roles controller and keep hitting numerous errors. The latest error is the following exception:
System.InvalidOperationException: 'Attaching an entity of type 'TRIZTools.Models.User' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.'
Here's a copy of the code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RoleAddToUser(string UserId, string RoleName)
{
User user = context.Users.Where(u => u.Id.Equals(UserId, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var userManager = new UserManager<User>(new UserStore<User>(new ApplicationDbContext()));
ViewBag.RolesForThisUser = userManager.GetRoles(user.Id);
var idResult = userManager.AddToRole(user.Id, RoleName);
if (user.AccountNew)
{
user.AccountNew = false;
userManager.Update(user);
}
It is failing at userManager.Update(user)
. I have tried the UpdateAsync, but that's failing too. Ideally what I want to do is set the user's new status to false, as this would make it easier to identify all the accounts that have been updated.
I am using Identity in my MVC framework and this method is not located in the AccountController.
Solution
With the assistance from @Rainman here is the the solution:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RoleAddToUser(string UserId, string RoleName)
{
User user = context.Users.Where(u => u.Id.Equals(UserId, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var userManager = new UserManager<User>(new UserStore<User>(new ApplicationDbContext()));
ViewBag.RolesForThisUser = userManager.GetRoles(user.Id);
var idResult = userManager.AddToRole(user.Id, RoleName);
if (user.AccountNew)
{
user.AccountNew = false;
context.SaveChanges(); //This fixed it!
}