I use ASP.NET Identity 2
in an MVC 5
项目,我想更新Student
数据通过使用UserManager.Update()
方法。然而,正如我继承自ApplicationUser
类,我需要映射Student
to ApplicationUser
在调用 update 方法之前。另一方面,当使用我也用于创建新学生的方法时,当我创建新实例而不是更新实例时,由于并发而出现错误。因为我很无聊使用解决问题AutoMapper
,我需要一个稳定的修复来解决问题,而不需要AutoMapper
。您能帮我解释一下如何解决这个问题吗?我通过StudentViewModel
到控制器中的 Update 方法,然后我需要将其映射到 Student,然后将它们传递给UserManager.Update()
方法如ApplicationUser
。另一方面,我想知道是否应该在控制器阶段检索并发送密码,而不是出于安全考虑而传递到视图?您能否也告诉我这个问题(在用户更新期间,我不更新密码,我必须将用户的密码保留在数据库中)。任何帮助,将不胜感激。
实体类:
public class ApplicationUser : IdentityUser<int, ApplicationUserLogin,
ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
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
as ApplicationUser
to the UserManager.Update()
方法(因为Student
类继承(因此is) 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)