通过ASP.NET身份2中的UserManager.Update()更新用户

我在MVC 5项目中使用ASP.NET Identity 2 ,我想使用UserManager.Update()方法更新Student数据。 但是,当我从ApplicationUser类inheritance时,我需要在调用update方法之前将Student映射到ApplicationUser 。 另一方面,当使用我也用于创建新Student的方法时,由于并发性而导致错误,因为我创建了一个新实例而不是更新。 由于我无法使用AutoMapper解决问题,我需要一个稳定的修复来解决问题,而无需AutoMapper 。 能否请您澄清如何解决这个问题? 我将StudentViewModel传递给StudentViewModel中的Update方法,然后我需要将它映射到Student,然后将它们作为ApplicationUser传递给UserManager.Update()方法。 另一方面,我想知道我是否应该在Controller阶段检索并发送密码,而不是为安全问题转到View? 你能否告诉我这个问题(在用户更新期间我不更新密码,我必须在数据库中保留用户的密码)。 任何帮助,将不胜感激。

实体类:

 public class ApplicationUser : IdentityUser, IUser { public string Name { get; set; } public string Surname { get; set; } //code omitted for brevity } public class Student: ApplicationUser { public int? Number { get; set; } } 

控制器:

 [HttpPost] [ValidateAntiForgeryToken] public JsonResult Update([Bind(Exclude = null)] StudentViewModel model) { if (ModelState.IsValid) { ApplicationUser user = UserManager.FindById(model.Id); user = new Student { Name = model.Name, Surname = model.Surname, UserName = model.UserName, Email = model.Email, PhoneNumber = model.PhoneNumber, Number = model.Number, //custom property PasswordHash = checkUser.PasswordHash }; UserManager.Update(user); } } 

没有必要将student作为ApplicationUser传递给UserManager.Update()方法(因为Student类inheritance(因此ApplicationUser )。

您的代码的问题在于您正在使用new Student运算符,从而创建新学生而不是更新现有学生。

像这样更改代码:

 // Get the existing student from the db var user = (Student)UserManager.FindById(model.Id); // Update it with the values from the view model user.Name = model.Name; user.Surname = model.Surname; user.UserName = model.UserName; user.Email = model.Email; user.PhoneNumber = model.PhoneNumber; user.Number = model.Number; //custom property user.PasswordHash = checkUser.PasswordHash; // Apply the changes if any to the db UserManager.Update(user); 

我对.netcore 1的回答

这项工作对我来说,我希望可以帮助他们

 var user = await _userManager.FindByIdAsync(applicationUser.Id); user.ChargeID = applicationUser.ChargeID; user.CenterID = applicationUser.CenterID; user.Name = applicationUser.Name; var result = await _userManager.UpdateAsync(user);