Asp.net MVC 用户管理器更新

Asp.net MVC UserManager Update

我尝试更新数据库中的用户数据,我从视图中获取价值并将这些数据分配给当前 user.Yet,我在更新用户数据时在该行中出错 var result = await UserManager.UpdateAsync(userAccount);。它被写为 一个或多个实体的验证失败。有关详细信息,请参阅 'EntityValidationErrors' 属性。。我该如何解决这个问题?谢谢

控制器:

public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ModifyAccount(ModifyUserAccountViewModel model)
    {
        var user = await UserManager.FindByIdAsync(int.Parse(User.Identity.GetUserId()));
        UserAccount userAccount = (UserAccount)user;
        userAccount.surname = model.surname;
        userAccount.name = model.name;
        userAccount.Email = model.email;
        var result = await UserManager.UpdateAsync(userAccount);
        if (result.Succeeded)
        {
            return RedirectToAction("Index", new { Message = "Account modyfyied successfully!" });
        }
        AddErrors(result);
        return View("Error");
     }

Startup.cs:

public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);          
    }

您可以按照@Praveen Prasad 在this post 中的建议尝试捕获异常以查看您遇到的验证错误:

 [HttpPost]
 [ValidateAntiForgeryToken]
 public async Task<ActionResult> ModifyAccount(ModifyUserAccountViewModel model)
 {
    var user = await UserManager.FindByIdAsync(int.Parse(User.Identity.GetUserId()));
    UserAccount userAccount = (UserAccount)user;
    userAccount.surname = model.surname;
    userAccount.name = model.name;
    userAccount.Email = model.email;

    try { 
      var result = await UserManager.UpdateAsync(userAccount);
    }
    catch (DbEntityValidationException dbEx)
    {
        foreach (var validationErrors in dbEx.EntityValidationErrors)
        {
            foreach (var validationError in validationErrors.ValidationErrors)
            {
               Trace.TraceInformation("Property: {0} Error: {1}", 
                                validationError.PropertyName, 
                                validationError.ErrorMessage);
            }
        }
    }

    if (result.Succeeded)
    {
       return RedirectToAction("Index", new { Message = "Account modyfyied successfully!" });
    }
    AddErrors(result);
    return View("Error");
}