public static async Task SeedDatabase(IdentityDataContext context,
                                              UserManager <IdentityUser> userManager,
                                              RoleManager <IdentityRole> roleManager)
        {
            if (context.Database.GetMigrations().Count() > 0 &&
                context.Database.GetPendingMigrations().Count() == 0)
            {
                IdentityRole role = await roleManager.FindByNameAsync(adminRole);

                IdentityUser user = await userManager.FindByNameAsync(adminUser);

                if (role == null)
                {
                    role = new IdentityRole(adminRole);
                    IdentityResult result = await roleManager.CreateAsync(role);

                    if (!result.Succeeded)
                    {
                        throw new Exception("Cannot create role: "
                                            + result.Errors.FirstOrDefault());
                    }
                }

                if (user == null)
                {
                    user = new IdentityUser(adminUser);
                    IdentityResult result
                        = await userManager.CreateAsync(user, adminPassword);

                    if (!result.Succeeded)
                    {
                        throw new Exception("Cannot create user: "******"Cannot add user to role: "
                                            + result.Errors.FirstOrDefault());
                    }
                }
            }
        }
Example #2
0
 public IdentitySeedData(IdentityDataContext context, UserManager <IdentityUser> userManager, RoleManager <IdentityRole> roleManager)
 {
     _context     = context;
     _userManager = userManager;
     _roleManager = roleManager;
 }