Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Call SampleData.Initialize(app.ApplicationServices).Wait(); in Startup.cs
- public class SampleData
- {
- public static async Task InitializeAsync(IServiceProvider serviceProvider)
- {
- IServiceScope serviceScope = serviceProvider.GetService<IServiceScopeFactory>().CreateScope();
- var context = serviceProvider.GetService<ApplicationDbContext>();
- var userManager = serviceProvider.GetService<UserManager<IdentityUser>>();
- var roleManager = serviceProvider.GetService<RoleManager<IdentityRole>>();
- string[] roles = new string[] { "Administrator", "User"};
- foreach (string roleName in roles)
- {
- var isExist = await roleManager.RoleExistsAsync(roleName);
- if (!isExist)
- {
- await roleManager.CreateAsync(new IdentityRole(roleName));
- }
- }
- var user = new IdentityUser
- {
- Email = "utharn.b@rmutsb.ac.th",
- UserName = "utharn.b@rmutsb.ac.th",
- SecurityStamp = Guid.NewGuid().ToString()
- };
- var currentUser = await userManager.FindByEmailAsync(user.Email);
- if (currentUser == null)
- {
- var result = await userManager.CreateAsync(user, "Secret123!");
- currentUser = await userManager.FindByEmailAsync(user.Email);
- }
- var isAdmin = await userManager.IsInRoleAsync(currentUser, "Administrator");
- if (!isAdmin)
- {
- await userManager.AddToRoleAsync(user, "Administrator");
- }
- var isUser = await userManager.IsInRoleAsync(currentUser, "User");
- if (!isUser)
- {
- await userManager.AddToRoleAsync(user, "User");
- }
- var containSampleBook = await context.Books.AnyAsync(b => b.Name == "Sample Book");
- if (!containSampleBook)
- {
- context.Books.Add(new Models.Book
- {
- Name = "Sample Book",
- Price = 100.00m
- });
- }
- await context.SaveChangesAsync();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement