Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
- {
- //will only try to seed if there is an outstanding migration
- if (!serviceScope.ServiceProvider.GetService<MyDataContext>().AllMigrationsApplied())
- {
- serviceScope.ServiceProvider.GetService<MyDataContext>().Database.Migrate();
- var roleManager = serviceScope.ServiceProvider.GetRequiredService<RoleManager<ApplicationRole>>();
- serviceScope.ServiceProvider.GetService<MyDataContext>().EnsureSeeded(roleManager);
- }
- }
- public static class DbContextExtension
- {
- public static bool AllMigrationsApplied(this MyDataContext context)
- {
- var applied = context.GetService<IHistoryRepository>()
- .GetAppliedMigrations()
- .Select(m => m.MigrationId);
- var total = context.GetService<IMigrationsAssembly>()
- .Migrations
- .Select(m => m.Key);
- return !total.Except(applied).Any();
- }
- public static async void EnsureSeeded(this MyDataContext context, RoleManager<ApplicationRole> roleManager)
- {
- var buildDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
- var filePath = buildDir + @"foo.txt";
- if (!context.Clients.Any())
- {
- var clients = JsonConvert.DeserializeObject<List<Client>>(File.ReadAllText(@"seed" + Path.DirectorySeparatorChar + "clients.json"));
- context.AddRange(clients);
- context.SaveChanges();
- }
- if (roleManager.Roles.Count() == 0)
- {
- string[] roleNames = { "Admin", "Manager", "Trader", "Public" };
- IdentityResult roleResult;
- foreach (var roleName in roleNames)
- {
- //creating the roles and seeding them to the database
- var roleExist = await roleManager.RoleExistsAsync(roleName);
- if (!roleExist)
- {
- roleResult = await roleManager.CreateAsync(new ApplicationRole(roleName));
- }
- }
- }
- if (!context.Users.Any())
- {
- var user = new ApplicationUser
- {
- FirstName = "Matt",
- LastName = "Flynn",
- Email = "test@test.com",
- NormalizedEmail = "TEST@TEST.COM",
- UserName = "test@test.com",
- NormalizedUserName = "TEST@TEST.COM",
- PhoneNumber = "+441234567891",
- EmailConfirmed = true,
- PhoneNumberConfirmed = true,
- SecurityStamp = Guid.NewGuid().ToString("D")
- };
- var password = new PasswordHasher<ApplicationUser>();
- var hashed = password.HashPassword(user, "password");
- user.PasswordHash = hashed;
- var userStore = new UserStore<ApplicationUser, ApplicationRole, MyDataContext, int>(context);
- await userStore.CreateAsync(user);
- await userStore.AddToRoleAsync(user, "Admin");
- await userStore.AddToRoleAsync(user, "Manager");
- await userStore.AddToRoleAsync(user, "Trader");
- await userStore.AddToRoleAsync(user, "Public");
- }
- }
- }
Add Comment
Please, Sign In to add comment