ASP.NET Core RC2 Seed Database

后端 未结 3 1694
梦毁少年i
梦毁少年i 2020-12-17 18:16

My problem is i am trying to seed an Entity Framework Core database with data and in my mind the below code show work. I\'ve realised that this should not be called in the <

3条回答
  •  清歌不尽
    2020-12-17 18:45

    Assuming you are using the built-in DI container, here is one way you can accomplish this.

    Reference your seed method in the Configure method of your startup class, and pass the IApplicationBuilder object as a parameter instead of the DbContext, like this:

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

    Next, modify your seed method to accept the IApplicationBuilder instance. Then you'll be able to spin up an instance of the DbContext, and perform your seed operation, like this:

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

提交回复
热议问题