0

我试图更新数据库中的用户数据,我从视图中获取值并将这些数据分配给当前用户。然而,当我更新用户的数据时,我在该行出现错误。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");
     }

启动.cs:

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

1 回答 1

0

您可以按照@Praveen Prasad 在这篇文章中的建议尝试捕获异常以查看您有哪些验证错误:

 [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");
}
于 2015-09-02T13:22:52.933 回答