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.
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?
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();
}
}