How to seed data in .NET Core 6 with Entity Framework?

Viewed 11304

I know how to seed data to a database with old .NET 5.0 in startup.cs file using my Seeder class with a Seed() method creating some initial data.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seeder seeder)
{
   seeder.Seed();

   ..............
   // other configurations
}

How do I do this in .NET 6.0? There is no place to add my Seeder class as an argument.

4 Answers

I solved a similar problem as follows:

Program.cs (.NET 6)

...
builder.Services.AddScoped<IDbInitializer, DbInitializer>(); //can be placed among other "AddScoped" - above: var app = builder.Build();   

...    
SeedDatabase(); //can be placed above app.UseStaticFiles();
...    
    void SeedDatabase() //can be placed at the very bottom under app.Run()
    {
        using (var scope = app.Services.CreateScope())
        {
            var dbInitializer = scope.ServiceProvider.GetRequiredService<IDbInitializer>();
            dbInitializer.Initialize();
        }
    }

I have never use your solution before. This is what I'm doing,

public class DataContext: DbContext
{
    public DataContext(DbContextOptions options) : base(options)
    {
        
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        new DbInitializer(modelBuilder).Seed();
    }
    
    // Db sets
}

And

public class DbInitializer
{
    private readonly ModelBuilder modelBuilder;

    public DbInitializer(ModelBuilder modelBuilder)
    {
        this.modelBuilder = modelBuilder;
    }

    public void Seed()
    {
        modelBuilder.Entity<User>().HasData(
               new User(){ Id = 1.... },
               new User(){ Id = 2.... },

        );
    }
}

Then run the command

dotnet ef migrations add .......

To create migration file

And

dotnet ef database update

To update db

In my case, I'm using Microsoft.AspNetCore.Identity and needed initialize application with default values in database using seed methods.

builder.Services.AddScoped<UserManager<ApplicationUser>>();
builder.Services.AddScoped<RoleManager<IdentityRole>>();

And after line containing

var app = builder.Build();

I have called the seeds methods:

using (var scope = app.Services.CreateScope())
{
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<Usuario>>();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
await DefaultRoles.SeedAsync(roleManager);
await DefaultAdmin.SeedAsync(userManager);
}

.NET 6.0

Use these links for detailed version:

Program.cs

var builder = WebApplication.CreateBuilder(args);

//Add services to the container.
builder.Services.AddDbContext<YourDbContext>(
    optionsBuilder => optionsBuilder.UseSqlServer("Your connection string goes here") //install - Microsoft.EntityFrameworkCore.SqlServer to use ".UseSqlServer" extension method
builder.Services.AddScoped<DbInitializer>();

var app = builder.Build();

//Configure the HTTP-request pipeline
if (app.Environment.IsDevelopment())
{
    app.UseItToSeedSqlServer();    //custom extension method to seed the DB
    //configure other services
}

app.Run();

DbInitializerExtension.cs

internal static class DbInitializerExtension
{
    public static IApplicationBuilder UseItToSeedSqlServer(this IApplicationBuilder app)
    {
        ArgumentNullException.ThrowIfNull(app, nameof(app));

        using var scope = app.ApplicationServices.CreateScope();
        var services = scope.ServiceProvider;
        try
        {
            var context = services.GetRequiredService<YourDbContext>();
            DbInitializer.Initialize(context);
        }
        catch (Exception ex)
        {

        }

        return app;
    }
}

DbInitializer.cs

internal class DbInitializer
{
    internal static void Initialize(YourDbContext dbContext)
    {
        ArgumentNullException.ThrowIfNull(dbContext, nameof(dbContext));
        dbContext.Database.EnsureCreated();
        if (dbContext.Users.Any()) return;

        var users = new User[]
        {
            new User{ Id = 1, Name = "Bruce Wayne" }
            //add other users
        };

        foreach(var user in users)
            dbContext.Users.Add(user);

        dbContext.SaveChanges();
    }
}
Related