From EF/MVC intro, just :
- dependency-inject your
DbContext (SchoolContext below) directly into Startup.Configure()*
- pass your
DbContext to a function (DbInitializer.Initialize below) which does something like:
- ensure Database is created or that it's migrated;
context.Database.EnsureCreated(); consider context.Database.Migrate();
- returns if already seeded
if (context.Students.Any()) { return; }
- else seed
context.Students.Add({...}); context.SaveChanges();
Like here:
public void Configure(..., ..., SchoolContext context)
{
...
DbInitializer.Initialize(context);
}
...
public static class DbInitializer
{
public static void Initialize(SchoolContext context)
{
context.Database.EnsureCreated();
// Look for any students.
if (context.Students.Any())
{
return; // DB has been seeded
}
var students = new Student[]
{
new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")}, ...
};
foreach (Student s in students)
{
context.Students.Add(s);
}
context.SaveChanges();
...
*Dependency-injecting into Startup.Configure() is why my answer is worthy (even though another answer is already accepted.)
- Dependency-injecting your
DbContext into Startup.Configure() is done in EF/MVC Intro
- No other answer here just dependency-injects into Configure; they either
GetService() and/or GetRequiredService(), or instantiate a new DbContext. You may not need that much code. Then again, you may need that much code, (i.e. if the Dependency-Injected DbContext was disposed, which is where the GetService() is necessary to create a new Scope.. Please downvote/edit/comment if I'm mistaken about something.