Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating user data - ASP.NET Identity

I've added custom fields to the ApplicationUser class
I've also created a form through which the user can enter/edit the fields.
However for some reason I'm not able to update the fields in the database.

[HttpPost] [ActionName("Edit")] [ValidateAntiForgeryToken] public async Task<ActionResult> Manage(EditProfileViewModel model) {     if (ModelState.IsValid)     {         // Get the current application user         var user = User.Identity.GetApplicationUser();          // Update the details         user.Name = new Name { First = model.FirstName, Last = model.LastName, Nickname = model.NickName };         user.Birthday = model.Birthdate;          // This is the part that doesn't work         var result = await UserManager.UpdateAsync(user);          // However, it always succeeds inspite of not updating the database         if (!result.Succeeded)         {             AddErrors(result);         }     }      return RedirectToAction("Manage"); } 

My problem is similar to MVC5 ApplicationUser custom properties, but that seems to use an older version of Identity because the IdentityManager class doesn't seem to exist.

Can someone guide me on how to update User info in the database?

UPDATE: If I include all the fields in the register form, all the values are stored in the appropriate field in a new record of the Users table from the database.

I don't know to make changes to the fields of an existing user (row in the users table). UserManager.UpdateAsync(user) doesn't work.

Also note my issue is more Identity oriented than EntityFramework

like image 487
galdin Avatar asked Dec 07 '13 17:12

galdin


1 Answers

OK... I spent hours trying to figure why userManager.updateAsync would not persist the user data that we edit ... until I reached the following conclusion:

The confusion arises from the fact that we create the UserManager in one line like this:

var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new MyDbContext())); 

...then we use manager.UpdateAsync( user ); but that will update the user in the context, and then we will need to save changes to the dbcontext of the Identity. So, the question is how to get the Identity DBcontext in the easiest way.

To solve this, we should not create the UserManager in one line ... and here is how I do it:

var store = new UserStore<ApplicationUser>(new MyDbContext()); var manager = new UserManager(store); 

then after updating the user by calling

manager.UpdateAsync(user); 

then you go to the context

var ctx = store.context; 

then

ctx.saveChanges(); 

wahooooooo...persisted :)

Hope this will help someone who pulled their hair for a few hours :P

like image 103
stackunderflow Avatar answered Oct 03 '22 01:10

stackunderflow