Details

Seed Data

To seed into the database

Create a DbInitializer class

Add the following method to seed roles

public static async Task SeedRoles(this IServiceProvider serviceProvider)
{
   using var scope = serviceProvider.CreateScope();
   var roleManager = scope.ServiceProvider
       .GetRequiredService<RoleManager<ApplicationRole>>();
       
   List<string> roles = ["Super Admin", "Admin", "User"];
   foreach (var role in roles)
   {
       if (!await roleManager.RoleExistsAsync(role.ToString()))
       {
           await roleManager.CreateAsync(new ApplicationRole { Name = role });
       }
   }
}

And add the following to seed users

public static async Task SeedDefaultUsers(this IServiceProvider serviceProvider)
{
   using var scope = serviceProvider.CreateScope();
   var userManager = scope.ServiceProvider
       .GetRequiredService<UserManager<ApplicationUser>>();
       
   var admin = new ApplicationUser()
   {
       FirstName = "FirsName",
       LastName = "LastName",
       Email = "example@gmail.com",
       UserName = "example@gmail.com",
       PhoneNumber = "000000000",
       Role = "Super Admin"
   };
   
   if (!userManager.Users.Any(a => a.Email.Equals(admin.Email)))
   {
       var result = await userManager.CreateAsync(admin, "Pa$$w0rD");
       if (result.Succeeded)
       {
           await userManager.AddToRoleAsync(admin, admin.Role);
       }
   }
}

Then call the static methods in Program.cs after calling builder.Build();

await app.Services.SeedRoles();
await app.Services.SeedDefaultUsers();

This will ensure that data is only ever seeded if it doesn't exist!