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

Jac*_*ack 15 c# asp.net-mvc automapper asp.net-identity asp.net-identity-2

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

实体类:

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; }
}
Run Code Online (Sandbox Code Playgroud)


控制器:

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Iva*_*oev 41

没有必要传递student作为ApplicationUserUserManager.Update()方法(因为Student类继承(因此)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);
Run Code Online (Sandbox Code Playgroud)

  • 不要删除答案.我借助你的宝贵帮助解决了这个问题.只需将第一行更改为**var user = UserManager.FindById(model.Id)作为学生;**在您的答案中:)非常感谢... (2认同)
  • 您能否更新您的答案,以便其他人也可以从中受益? (2认同)

小智 7

我在 .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);
Run Code Online (Sandbox Code Playgroud)