Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Microsoft.AspNet.Identity;
- using Microsoft.AspNet.Identity.EntityFramework;
- using SharedLibrary.Models;
- using System;
- using System.Collections.Generic;
- using System.Data.Entity;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Web;
- namespace SharedLibrary.Utils
- {
- public class AppDatabaseInitializator
- {
- public static async void SeedAsync(ApplicationDbContext context)
- {
- InitializeRoles(context);
- InitializeUsers(context);
- InitializeBooks(context);
- }
- private static void InitializeUsers(ApplicationDbContext context)
- {
- var userStore = new UserStore<ApplicationUser>(context);
- var userManager = new ApplicationUserManager(userStore);
- var user1 = new ApplicationUser() { FirstName = "Mitre", LastName = "Mitrevski", Email = "mitre.mitrevski@gmail.com" };
- var user2 = new ApplicationUser() { FirstName = "Petre", LastName = "Petrevski", Email = "petre.petrevski@gmail.com" };
- var user3 = new ApplicationUser() { FirstName = "Stanko", LastName = "Stankovski", Email = "stanko.stankovski@gmail.com" };
- CreateUserAsync(user1, userManager);
- CreateUserAsync(user2, userManager);
- CreateUserAsync(user3, userManager);
- }
- private static async void CreateUserAsync(ApplicationUser user, UserManager<ApplicationUser> userManager)
- {
- var appUser = await userManager.FindByEmailAsync(user.Email);
- if (appUser != null)
- {
- await userManager.CreateAsync(appUser, "Test123@");
- }
- return;
- }
- private static void InitializeBooks(ApplicationDbContext context)
- {
- List<Book> books = new List<Book>() {
- new Book() { Id = 1, Name = "The Alchemist", Authors = "Paulo Coelho" },
- new Book() { Id = 2, Name = "The Very Hungry Caterpillar", Authors = "Eric Carie" },
- new Book() { Id = 3, Name = "Goodnight Moon", Authors = "Margaret Wise Brown" },
- new Book() { Name = "The Outsider: A Novel", Authors = "Stephen King" },
- new Book() { Name = "Just Mercy: A Story of Justice and Redemption", Authors = "Bryan Stevenson" }
- };
- context.Books.AddRange(books);
- context.SaveChanges();
- }
- private static void InitializeRoles(ApplicationDbContext context)
- {
- var roles = context.Roles.ToList();
- var adminRole = new IdentityRole("Administrator");
- var editorRole = new IdentityRole("Editor");
- var standardUserRole = new IdentityRole("StandardUser");
- if (roles == null || roles.Count == 0)
- {
- context.Roles.Add(adminRole);
- context.Roles.Add(editorRole);
- context.Roles.Add(standardUserRole);
- } else {
- if (!roles.Any(role => role.Name == "Administrator")) context.Roles.Add(adminRole);
- if (!roles.Any(role => role.Name == "Editor")) context.Roles.Add(editorRole);
- if (!roles.Any(role => role.Name == "StandardUser")) context.Roles.Add(standardUserRole);
- }
- context.SaveChanges();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement