How to register a user with Identity, with the data already entered?

Asked

Viewed 151 times

1

I have a method that inserts several data from an excel spreadsheet into the database, but there are some data, such as email, password, or concurrencyStamp (set as NULL), so I can’t change users' data through 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 entities Were Loaded. See http://go.microsoft.com/fwlink/? Linkid=527962 for information on understanding and Handling optimistic concurrency exceptions. Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.Throwaggregateupdateconcurrencyexception(int commandIndex, int expectedRowsAffected, int rowsAffected)

  • It’s really ASP.NET Core?

  • Yes, . net core at least

  • Ah, okay. Just checking in.

1 answer

1


I did, 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();
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.