Share via


Seed Users and Roles in an ASP.NET MVC Application

Question

Tuesday, February 6, 2018 9:21 AM

How to Seed Users and Roles in an ASP.NET MVC Application ?

All replies (3)

Tuesday, February 6, 2018 12:13 PM ✅Answered

Refer following link

http://jorgeramon.me/2015/how-to-seed-users-and-roles-in-an-asp-net-mvc-application/


Wednesday, February 7, 2018 6:13 AM ✅Answered

Hi priyu323,

It seems you want to use Seed to add data to Users and Roles table. It's similar to other ordinary tables, the biggest difference is we need to hash the password manually.

protected override void Seed(AuthorizeDemo.Models.ApplicationDbContext context)
{
    var passwordHash = new PasswordHasher();
    string password = passwordHash.HashPassword("Password@123");
    context.Users.AddOrUpdate(u => u.UserName,
        new ApplicationUser
        {
            UserName = "[email protected]",
            PasswordHash = password,
            PhoneNumber = "12345678911",
            Email= "[email protected]"
        });
    context.Roles.AddOrUpdate(
        new IdentityRole {Id="1", Name = "Admin" }
        );
}

Or you can the UserStore. In this approach you don’t have to take care of password hashing.

if (!(context.Users.Any(u => u.UserName == "[email protected]")))
{
    var userStore = new UserStore<ApplicationUser>(context);
    var userManager = new UserManager<ApplicationUser>(userStore);
    var userToInsert = new ApplicationUser { UserName = "[email protected]", PhoneNumber = "12345678911", Email = "[email protected]" };
    userManager.Create(userToInsert, "Password@123");
}

Best Regards,

Daisy


Wednesday, February 7, 2018 10:45 AM

Hello X.Daisy

Thank you for the code. The code given you provide, the same thing I was searching for. Its really helpful for me. Thank You again!