How to register a user with identity, with the data already inserted?

1

I have a method that inserts several data from an excel spreadsheet into the database, but there is some data, such as email, password, or concurrencyStamp (set to NULL), so I can not change user data by means of the code.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> RegisterUserCreated(ApplicationUser user)
    {
        if (ModelState.IsValid)
        {
            user.UserName = user.Email;
            user.NormalizedUserName = user.Email.ToTitleCase();
            user.NormalizedEmail = user.Email.ToTitleCase();

            if (user.Id_Matricula != null) user.Id = (int) user.Id_Matricula;

            user.Departamento = _context.TbDepartamentos.Find(user.Id_Departamento);

            var password = new PasswordHasher<ApplicationUser>();
            var passwordHash = password.HashPassword(user, "Senha");
            user.PasswordHash = passwordHash;

            user.ConcurrencyStamp = await _userManager.GenerateConcurrencyStampAsync(user);
            await _userManager.UpdateSecurityStampAsync(user);

            _context.ApplicationUsers.Update(user);
            _context.SaveChanges();
        }

    }

Error

  

An unhandled exception occurred while processing the request.

     

DbUpdateConcurrencyException: Database operation expected to affect 1 row (s) but actually affected 0 row (s). Data may have been modified or deleted since characters were loaded. See link for information on understanding and handling optimistic concurrency exceptions.   Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ThrowAggregateUpdateConcurrencyException (int commandIndex, int expectedRowsAffected, int rowsAffected)

    
asked by anonymous 22.05.2017 / 19:01

1 answer

1

I managed, using findByIdAsync()

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RegisterUserCreated(ApplicationUser user)
{
    if (ModelState.IsValid)
    {
        var user = await _userManager.FindByIdAsync(model.Id_Matricula.ToString());

            user.Dt_Contratacao = model.Dt_Contratacao;
            user.Email = model.Email;
            var b = await _userManager.SetUserNameAsync(user, user.Email);
            var a = await _userManager.UpdateSecurityStampAsync(user);
            var c = await _userManager.AddPasswordAsync(user, "TESTEteste@#123456789");


            _context.ApplicationUsers.Update(user);
            _context.SaveChanges();
    }

}
    
22.05.2017 / 20:01