Database seeder

public static class DatabaseSeeder
{
public static async Task SeedData(IServiceProvider provider)
{
var userManager = provider.GetRequiredService>();
var roleManager = provider.GetRequiredService>();
var db = provi…


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


Print Share Comment Cite Upload Translate Updates
APA

Mahir Xalilov | Sciencx (2025-01-23T01:14:28+00:00) Database seeder. Retrieved from https://www.scien.cx/2025/01/23/database-seeder/

MLA
" » Database seeder." Mahir Xalilov | Sciencx - Thursday January 23, 2025, https://www.scien.cx/2025/01/23/database-seeder/
HARVARD
Mahir Xalilov | Sciencx Thursday January 23, 2025 » Database seeder., viewed ,<https://www.scien.cx/2025/01/23/database-seeder/>
VANCOUVER
Mahir Xalilov | Sciencx - » Database seeder. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/01/23/database-seeder/
CHICAGO
" » Database seeder." Mahir Xalilov | Sciencx - Accessed . https://www.scien.cx/2025/01/23/database-seeder/
IEEE
" » Database seeder." Mahir Xalilov | Sciencx [Online]. Available: https://www.scien.cx/2025/01/23/database-seeder/. [Accessed: ]
rf:citation
» Database seeder | Mahir Xalilov | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.