This content originally appeared on DEV Community and was authored by Mahir Xalilov
public static class DatabaseSeeder
{
public static async Task SeedData(IServiceProvider provider)
{
var userManager = provider.GetRequiredService>();
var roleManager = provider.GetRequiredService>();
var db = provider.GetRequiredService();
db.Database.Migrate();
string[] roles = { "Admin", "User" };
foreach ( var role in roles )
{
if (!await roleManager.RoleExistsAsync(role))
{
await roleManager.CreateAsync(new IdentityRole(role));
}
}
string email = "admin@gmail.com";
string userName = "admin";
string password = "Admin123!";
if (await userManager.FindByEmailAsync(email) is null)
{
IdentityUser user = new IdentityUser
{
Email = email,
UserName = userName,
EmailConfirmed = true,
};
IdentityResult result = await userManager.CreateAsync(user,password);
if (result.Succeeded)
{
await userManager.AddToRoleAsync(user,"Admin");
}
}
}
}
This content originally appeared on DEV Community and was authored by Mahir Xalilov

Mahir Xalilov | Sciencx (2025-01-23T01:14:28+00:00) Database seeder. Retrieved from https://www.scien.cx/2025/01/23/database-seeder/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.