Error when registering user

Asked

Viewed 68 times

1

When I try to create a second user, with ASP.NET MVC, presents me with a mistake:

Violation of PRIMARY KEY Constraint 'Pk_dbo.Aspnetusers'. Cannot Insert Duplicate key in Object 'dbo.Aspnetusers'. The Duplicate key value is (00000000-0000-0000-0000-000000000000). The statement has been terminated.

Man controller is like this:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new Usuario { Id = new Guid(), UserName = model.UserName, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

and my ViewModel:

 public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [Display(Name = "Usuário")]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

What am I doing wrong ?

1 answer

4


Try to change Id = new Guid() forId = Guid.NewGuid(). The new Guid will create a new key with zeros, and as you must already have a registered user happens to duplicate primary key Exception.

See working on dotnet fiddle.

Browser other questions tagged

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