For EF Core RTM 1.0 and ASP.NET Core RTM 1.0
First create the seed method. Here because we are out the scope of the current request, we must create it manulally:
using System.Collections.Generic;
using System.Linq;
using Core1RtmEmptyTest.Entities;
using Microsoft.Extensions.DependencyInjection;
namespace Core1RtmEmptyTest.Migrations
{
public static class ApplicationDbContextSeedData
{
public static void SeedData(this IServiceScopeFactory scopeFactory)
{
using (var serviceScope = scopeFactory.CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
if (!context.Persons.Any())
{
var persons = new List<Person>
{
new Person
{
FirstName = "Admin",
LastName = "User"
}
};
context.AddRange(persons);
context.SaveChanges();
}
}
}
}
}
Then specify the correct life time of the ApplicationDbContext
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(ServiceLifetime.Scoped);
And finally call the SeedData()
method from the Configure
method
public void Configure(IServiceScopeFactory scopeFactory)
{
scopeFactory.SeedData();