MVC5 Identity UserManager.Update(user) not working

asp.net-mvc-5 c# entity-framework owin

Question

I've never used code first in MVC5 user management before. I can edit user registration, but I cannot change passwords. I have searched the internet extensively and have read every UserManager-related question posted on this site. Update(user) isn't functioning.

using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace _100..Models
{

    public class ApplicationUser : IdentityUser
    {
        public virtual PersonalInfo PersonalInfo { get; set; }
        public virtual BillingInfo BillingInfo { get; set; }
        public virtual DeliveryInfo DeliveryInfo { get; set; }
        public Chapters Chapter { get; set; }
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class PersonalInfo
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class BillingInfo
    {
        public int ID { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
    }

    public class DeliveryInfo
    {
        public int ID { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
    }


    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false){}

        public DbSet<PersonalInfo> PersonalInfo { get; set; }
        public DbSet<BillingInfo> BillingInfo { get; set; }
        public DbSet<DeliveryInfo> DeliveryInfo { get; set; }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
}

And this is what I did.

[HttpPost]
        public async Task<ActionResult> UpdateRegisteration(ApplicationUser user)
        {
            var result = await UserManager.UpdateAsync(user);
            return RedirectToAction("Index", "Home");
        }

Although the update function returns success and the user object contains the changed data when it hits the action, the database is not actually updated.

1
3
1/9/2015 5:09:46 PM

Popular Answer

This repair has a number of levels. I started by running UserManager. The user object I received from my updateRegistration view was updated. Because EF believed it to be a new object, it raised the internal error "UserName already exists" and reported failure while still failing. In order to update the entity state to modified, I had to build a dbContext. But I soon discovered that in order to set the UserName, I also needed to build a user object from the updated users ID. Otherwise, the update wouldn't work. I discovered that the PasswordHash needed to be updated else it would be null. Then I discovered that in order to avoid an error during the login procedure, I also needed to update the SecurityStamp. Below is what I did.

 [HttpPost]
public async Task<ActionResult> UpdateRegisteration(ApplicationUser UpdatedUser)
{
    var SavedUser = await UserManager.FindByIdAsync(UpdatedUser.Id);

    try
    {
        UpdatedUser.SecurityStamp = SavedUser.SecurityStamp;
        UpdatedUser.PasswordHash = SavedUser.PasswordHash;
        UpdatedUser.UserName = SavedUser.UserName;
        UpdatedUser.Id = SavedUser.Id;
        UpdatedUser.PersonalInfo.ID = SavedUser.PersonalInfo.ID;
        UpdatedUser.BillingInfo.ID = SavedUser.BillingInfo.ID;
        UpdatedUser.DeliveryInfo.ID = SavedUser.DeliveryInfo.ID;

        ApplicationDbContext db = new ApplicationDbContext();
        db.Entry(UpdatedUser).State = EntityState.Modified;
        db.Entry(UpdatedUser.PersonalInfo).State = EntityState.Modified;
        db.Entry(UpdatedUser.BillingInfo).State = EntityState.Modified;
        db.Entry(UpdatedUser.DeliveryInfo).State = EntityState.Modified;
        await db.SaveChangesAsync();

        //            var result = await UserManager.UpdateAsync(SavedUser);
        return RedirectToAction("Index", "Home");
    }
    catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
    {
        Exception raise = dbEx;
        foreach (var validationErrors in dbEx.EntityValidationErrors)
        {
            foreach (var validationError in validationErrors.ValidationErrors)
            {
                string message = string.Format("{0}:{1}",
                    validationErrors.Entry.Entity.ToString(),
                    validationError.ErrorMessage);
                // raise a new exception nesting
                // the current instance as InnerException
                raise = new InvalidOperationException(message, raise);
            }
        }
        throw raise;
    }
}
1
1/9/2015 8:25:16 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow