Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Identity 2.0 update user

Tags:

Having a problem with saving user changes to the database, like changing the person's name. I'm using the IdentityModel that is automatically created in a new VS2013 web project using individual authentication. Sadly, the template doesn't allow you to change any user information, other than changing roles. I'm looking around via google, I haven't found much. Anyone implement updating using the base identity code?

This is the closest thing I found:

Updating user data - Asp.net Identity

I haven't been successful at incorporating default template. I've just started using Identity this week, so it might be my lack of understanding that's the problem.

var updatedUser = new ApplicationUser             {                 Id = model.UserId,                 UserName = model.UserName,                 CustomerId = model.CustomerId,                 Email = model.EmailAddress,                 FirstName = model.FirstName,                 LastName = model.LastName,                 PhoneNumber = model.PhoneNumber,                                 };  ... var result = await UserManager.UpdateAsync(updatedUser); 

My UserManager is created like this:

return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); 

I get the following error in the browser:

Attaching an entity of type 'ApplicationUser' 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

Thanks

like image 431
BCarlson Avatar asked Apr 03 '14 13:04

BCarlson


1 Answers

The problem I had was I creating an ApplicationUser and saved the object to the database. Since Identity uses Entity Framework under the covers, the entity state of the "updatedUser" object is Added. So Entity Framework tried to INSERT in to the Identity database, causing the conflict. So, you have to get the user and update the returned user object for Entity Framework to know that the entity state is Modified. Here's the working code:

var user = await UserManager.FindByIdAsync(model.UserId);  user.Email = model.EmailAddress; user.CustomerId = model.CustomerId; user.FirstName = model.FirstName; user.PhoneNumber = model.PhoneNumber; user.LastName = model.LastName;  var result = await UserManager.UpdateAsync(user); 
like image 122
BCarlson Avatar answered Sep 20 '22 05:09

BCarlson