ASP.NET Core RC2 Seed Database

后端 未结 3 1687
梦毁少年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:56

    You could also use from the Startup.cs ConfigureServices method to make your ApplicationDbContext available (Registering the dbcontext as a service):

    public void ConfigureServices(IServiceCollection services)
    {
       var connectionString = Startup.Configuration["connectionStrings:DBConnectionString"];//this line is not that relevant, the most important thing is registering the DbContext
                services.AddDbContext(o => o.UseSqlServer(connectionString));
    }
    

    and then add your ApplicationDbContext as dependency in your Configure method which will call your seed extension method.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext myApplicationDbContext)
    {
        //...
        myApplicationDbContext.Seed();
    }
    

    Finally the seed method could do a quick check on an important table, because perhaps recreating the db is too heavy:

    public void Seed()
    {
     //....      
     if(context.Countries.Any())
       return;
     //...
    }
    

    I hope it helps you or someone else, at least as another option.

提交回复
热议问题