Seeding Data with Entity Framework 3.0 with Model or Migration?

.net-core asp-net-core-spa-services entity-framework-core

Question

With the latest ASP.NET Core 3, and EF Core 3, I want to seed data as I've done in previous version of EF. I notice that in the Microsoft docs, they point at this code as an example of how to seed.

https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/core/Modeling/DataSeeding/Migrations

It updates the migration with code like this:

        migrationBuilder.InsertData(
            table: "Posts",
            columns: new[] { "PostId", "BlogId", "Content", "Title", "AuthorName_First", "AuthorName_Last" },
            values: new object[] { 1, 1, "Test 1", "First post", "Andriy", "Svyryd" });

        migrationBuilder.InsertData(
            table: "Posts",
            columns: new[] { "PostId", "BlogId", "Content", "Title", "AuthorName_First", "AuthorName_Last" },
            values: new object[] { 2, 1, "Test 2", "Second post", "Diego", "Vega" });

This seems "uncomfortable" to me as the way I've learned to init all my data and tables is to remove my migrations folder and then recreate the database. If I manually update a migration, then I'm stuck keeping this migration forever.

Is there a better way to handle seeding data in EF Core 3? Maybe with dbContext or somehow putting something in the model class itself?

1
0
11/5/2019 6:00:07 PM

Popular Answer

You can seed data in Program.cs. Like following.

public static async Task Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    using (var scope = host.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        await SeedData.EnsureSeedData(scope.ServiceProvider);
    }

    host.Run();
}

Create a class SeedData and in it write your seeding logic.

public static async Task EnsureSeedData(IServiceProvider provider)
{
    var dbContext = provider.GetRequiredService<MyDbContext>();
    await dbContext.Database.MigrateAsync();

    if(!await dbContext.MyTables.AnyAsync())
    {
        await dbContext.MyTables.AddAsync(new MyTable {})
        await dbContext.SaveChangesAsync();
    }
}
0
11/6/2019 4:29:03 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow