I am using asp.net identity to create new user but getting error:
Cannot insert the value NULL into column \'Id\', table \'Mydb.dbo.AspNetUsers\'; c
The inconsistency i found, in ApplicationUser
class you are declaring property Id
and Email
which is wrong because the IdentityUser
class already have those properties. This may arise the issue. But you can override them if necessary. Also the constructor you are using isn't necessary. The ApplicationUser
class should be:
public class ApplicationUser : IdentityUser
{
public async Task GenerateUserIdentityAsync(UserManager manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
this.SecurityStamp = Guid.NewGuid().ToString();
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string Role { get; set; }
public bool? IsActive { get; set; }
public int? CreatedBy { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? LastLogin { get; set; }
}
Second thing, you are creating the user inside Login
action which is also not valid. you should do it inside Register
action. Following in an example:
public async Task Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
FirstName = "Abc",
LastName = "Pqr",
UserName = "Abc@yahoo.com",
Email= model.Email,
Password= model.Password,
PasswordHash = UserManager.PasswordHasher.HashPassword(model.Password),
SecurityStamp = Guid.NewGuid().ToString()
};
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
Hope this will help :)