I know the question about .NET 6.0 but I think it's in the same concepts.
In my case, I'm using .NET 8.0, and using Microsoft.AspNetCore.Identity so I need to initialize the application with default values (Defulat User and Defulat Roles) in the database using seed methods.
So First I create a class and inside it, I define an enum "Contains the roles I have" and write the main info related to the default user "Name, Email, Password, Role...etc".
Then I create a class called ApplicationDbContextSeed
:
public class ApplicationDbContextSeed
{
public async Task<bool> SeedEssentialsAsync(UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
{
//Seed Roles
await roleManager.CreateAsync(new IdentityRole(Authorization.Roles.SuperUser.ToString()));
await roleManager.CreateAsync(new IdentityRole(Authorization.Roles.User.ToString()));
//Seed Default User
var defaultUser = new ApplicationUser
{
Firstname= Authorization.default_Firstname,
Lastrname= Authorization.default_Lastname,
UserName = Authorization.default_username,
Email = Authorization.default_email,
EmailConfirmed = true,
PhoneNumberConfirmed = true,
IsPasswordChanged = true,
IsActive = true
};
if (userManager.Users.All(u => u.Id != defaultUser.Id))
{
await userManager.CreateAsync(defaultUser, Authorization.default_password);
await userManager.AddToRoleAsync(defaultUser, Authorization.superuser_role.ToString());
}
return true;
}
}
In Program.cs :
var app = builder.Build();
if (args.Length == 1 && args[0].ToLower() == "seeddata")
await SeedData(app);
async Task SeedData(IHost app)
{
var scopedFactory = app.Services.GetService<IServiceScopeFactory>();
using (var scope = scopedFactory?.CreateScope())
{
var service = scope?.ServiceProvider.GetService<ApplicationDbContextSeed>();
var userManager = scope?.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = scope?.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
await service.SeedEssentialsAsync(userManager, roleManager);
}
}
After I created my first migration Add-Migration InitialCreate
and created the database using the statement Update-database
, the tables were empty, and I filled it with the initial data using the statement dotnet run seeddata
Hope it helps anybody stuck in this part.