Seed Entities AND Users, Roles?
Solution 1:
I don't seed from the migration, instead use the context db initializer. My context derives from IdentityDbContext so I use this method to seed users and roles:
Call an initializer from ctor:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
private readonly IHttpContextBaseWrapper _httpContextBaseWrapper;
static ApplicationDbContext()
{
// Set the database intializer which is run once during application start
// This seeds the database with admin user credentials and admin role
Database.SetInitializer(new ApplicationDbInitializer());
}
...
Then my seed code:
public class ApplicationDbInitializer : CreateDatabaseIfNotExists<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
InitializeIdentityForEF(context);
base.Seed(context);
}
public static void InitializeIdentityForEF(ApplicationDbContext db)
{
if (!db.Users.Any())
{
var roleStore = new RoleStore<IdentityRole>(db);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(db);
var userManager = new UserManager<ApplicationUser>(userStore);
// Add missing roles
var role = roleManager.FindByName("Admin");
if (role == null)
{
role = new IdentityRole("Admin");
roleManager.Create(role);
}
// Create test users
var user = userManager.FindByName("admin");
if (user == null)
{
var newUser = new ApplicationUser()
{
UserName = "admin",
FirstName = "Admin",
LastName = "User",
Email = "[email protected]",
PhoneNumber = "5551234567",
MustChangePassword = false
};
userManager.Create(newUser, "Password1");
userManager.SetLockoutEnabled(newUser.Id, false);
userManager.AddToRole(newUser.Id, "Admin");
}
...