2015-01-09 4 views
3

사용자 관리를 위해 MVC5에서 코드를 처음 사용합니다. 비밀번호를 변경할 수는 있지만 사용자 등록을 업데이트 할 수 없습니다. 나는 인터넷을 샅샅이 뒤지고이 사이트에서 UserManager.Update (사용자)와 관련된 모든 질문을 문자 그대로 보지 않습니다.MVC5 Identity UserManager.Update (user) not working

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(); 
     } 
    } 
} 

그리고 여기 내가이 작업을 명중하고 업데이트 방법은 성공을 반환 할 때 사용자 개체가 업데이트 된 데이터를 가지고 있음을 확인했다

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

내 행동입니다하지만 실제로 데이터베이스를 업데이트하지 않습니다.

+0

'UserManager' 선언을 게시 할 수 있습니까? 'DbContext'는이'UserManager'를 사용합니까? – Ofiris

+0

내 AccountController의 생성자로 전달됩니다. '코드'public AccountController (ApplicationUserManager userManager, ApplicationSignInManager signInManager) { UserManager = userManager; SignInManager = signInManager; } – Nayls

+0

그리고 어디서 만들어 졌습니까? – Ofiris

답변

1

이 수정에는 몇 가지 레이어가 있습니다. 먼저 UserManager.Update를 실행했을 때 updateRegistration 뷰에서받은 사용자 객체에 대한 것이 었습니다. EF는 그것이 새로운 객체라고 생각하고 "UserName already exists"라는 내부 오류를 발생시키고 실패했지만 성공을보고했습니다. 그래서 dbContext를 만들고 엔티티 상태를 수정해야했습니다. 그러나 UserName을 설정하기 위해 업데이트 된 사용자 ID로 사용자 개체를 만들어야했거나 업데이트하지 못했습니다. PasswordHash를 업데이트해야한다는 사실을 발견했거나 null 일 것입니다. 그런 다음 SecurityStamp를 업데이트해야하거나 로그인 프로세스가 오류를 발생시키는 것으로 나타났습니다. 나의 행동은 아래와 같습니다.

[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; 
    } 
}