How to create a user and get the newly created ID with ASP.NET Identity

Using the IdentityUser or using a class that inherits from IdentityUser, makes the model having an UserId attribute. Using following code, passing the user to the method, will fill up the Id.

var user = model.GetUser();
var result = await UserManager.CreateAsync(user, model.Password);

if (result.Succeeded)
    result = UserManager.AddToRole(user.Id, "User");

The model.GetUser() returns an object of the ApplicationUser or IdentityUser

public ApplicationUser GetUser()
{
    var user = new ApplicationUser
    {
        UserName = UserName,
        FirstName = FirstName,
        LastName = LastName,
        Email = Email,
        ...
    };

    return user;
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)