Monday, October 15, 2018

Call out to a database seeder from Startup.cs!

Page 190 of "ASP.NET Core 2 and Angular 5" by Valerio De Sanctis will have you putting something like this in the Configure method:

using (var serviceScope = app.ApplicationServices
      .GetRequiredService<IServiceScopeFactory>().CreateScope())
{
   var dbContext = serviceScope.ServiceProvider.GetService<MyDbContext>();
   dbContext.Database.Migrate();
   MySeeder.Seed(dbContext);
}

 
 

The point of the seeder class is to seed a database which probably doesn't exist yet with dummy objects in EF Core implementations. You want to do this after the first migration. The seeder class will add objects to a DbContext implementation (a custom class that implements DbContext) and then save changes.

No comments:

Post a Comment