ASP.NET Core Web API - seeding data in .NET Core 6 using Entity Framework

Viewed 615

In ASP.NET Core 6 Web API, I am implementing EF migration seeding. When I used .NET Core 5, I applied it in Startup.cs and it works there.

public static class AppDbContextSeed
{
    public static void SeedData(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
    {
        SeedRoles(roleManager);
        SeedUsers(userManager);
    }

    public static void SeedRoles(RoleManager<ApplicationRole> roleManager)
    {
        if (!roleManager.RoleExistsAsync("Admin").Result)
        {
            ApplicationRole role = new ApplicationRole();
            role.Name = "Admin";
            IdentityResult roleResult = roleManager.
            CreateAsync(role).Result;
        }

        if (!roleManager.RoleExistsAsync("Student").Result)
        {
            ApplicationRole role = new ApplicationRole();
            role.Name = "Student";
            IdentityResult roleResult = roleManager.
            CreateAsync(role).Result;
        }
    }

    public static void SeedUsers(UserManager<ApplicationUser> userManager)
    {
        if (userManager.FindByNameAsync("admin").Result == null)
        {
            ApplicationUser user = new ApplicationUser()
            {
                UserName = "admin",
                Email = "admin@africa.email.com",
                FirstName = "AdminFN",
                LastName = "AdminLN",
                NormalizedUserName = "ADMIN"
            };
            IdentityResult result = userManager.CreateAsync
            (user, "Admin*123").Result;

            if (result.Succeeded)
            {
                userManager.AddToRoleAsync(user, "Admin").Wait();
            }
        }
    }
}

But now I am using .NET Core 6. So when I applied this in Program.cs:

public void Configure(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
{
    // DB Seeding
    AppDbContextSeed.SeedData(userManager, roleManager);
}

I got this error:

The local function 'Config' is declared but never used

Error CS0106: the modifier 'public' is not valid for this item

How do I correct the error and replicate this in .NET Core 6?

Thank you.

1 Answers

I had to edit my last answer, the example I gave was for .net5. Here is .net 6, I haven't tested it myself but it should work.

var builder = WebApplication.CreateBuilder(args);


// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();


var app = builder.Build();


Configure(app);

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();


void Configure(WebApplication host)
{
    using var scope = host.Services.CreateScope();
    var services = scope.ServiceProvider;

    try
    {
        var dbContext = services.GetRequiredService<MyDatabaseContext>();

        if (dbContext.Database.IsSqlServer())
        {
            dbContext.Database.Migrate();
        }

        var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
        var roleManager = services.GetRequiredService<RoleManager<ApplicationRole>>();
        AppDbContextSeed.SeedData(userManager, roleManager);
    }
    catch (Exception ex)
    {
        //Log some error
        throw;
    }
}
Related