ASP.NET Core RC2种子数据库

Ada*_*m H 11 c# entity-framework-core asp.net-core asp.net-core-1.0

我的问题是我试图用数据种子实体框架核心数据库,在我看来下面的代码显示工作.我已经意识到这不应该在ApplicationDbContext构造函数中调用,应该从中调用,startup但我不知道如何做到这一点.

编辑:根据Ketrex提供的解决方案,我的解决方案如下:

Startup.cs:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        ... 

        app.ApplicationServices.GetRequiredService<ApplicationDbContext>().Seed();
    }
Run Code Online (Sandbox Code Playgroud)

种子延伸:

public static class DbContextExtensions
{
    public static void Seed(this ApplicationDbContext context)
    {
        // Perform database delete and create
        context.Database.EnsureDeleted();
        context.Database.EnsureCreated();

        // Perform seed operations
        AddCountries(context);
        AddAreas(context);
        AddGrades(context);
        AddCrags(context);
        AddClimbs(context);

        // Save changes and release resources
        context.SaveChanges();
        context.Dispose();
    }

    private static void AddCountries(ApplicationDbContext context)
    {
        context.AddRange(
            new Country { Name = "England", Code = "En" },
            new Country { Name = "France", Code = "Fr" }
            );
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

我知道在实体框架的优先级列表中播种数据库是相当高的,但如果有一些关于如何实现这个微不足道的任务或者至少提供临时工作的文档会很好.如果有人可以就如何做到这一点提供一些指导,我们将不胜感激.我觉得我接近一个解决方案,但只是不能把它拼凑在一起.

谢谢你的帮助.

cyg*_*nim 11

假设您使用的是内置DI容器,这是一种可以实现此目的的方法.

在启动类的Configure方法中引用种子方法,并将IApplicationBuilder对象作为参数而不是DbContext传递,如下所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //...
    // Put this at the end of your configure method
    DbContextSeedData.Seed(app);
}
Run Code Online (Sandbox Code Playgroud)

接下来,修改种子方法以接受IApplicationBuilder实例.然后你就可以启动DbContext的一个实例,并执行你的种子操作,如下所示:

public static void Seed(IApplicationBuilder app)
{
    // Get an instance of the DbContext from the DI container
    using (var context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>())
    {
        // perform database delete
        context.Database.EnsureDeleted;
        //... perform other seed operations
    }
}
Run Code Online (Sandbox Code Playgroud)