auto create database in Entity Framework Core

前端 未结 5 748
南笙
南笙 2020-11-29 17:43

My application which is being ported to .NET core will use the new EF Core with SQLite. I want to automatically create the database and table structures when the app is firs

5条回答
  •  天命终不由人
    2020-11-29 18:08

    If you have created the migrations, you could execute them in the Startup.cs as follows.

     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
     {
          using (var serviceScope = app.ApplicationServices.GetService().CreateScope())
          {
                var context = serviceScope.ServiceProvider.GetRequiredService();
                context.Database.Migrate();
          }
    
          ...
    

    This will create the database and the tables using your added migrations.

    If your not using Entity Framework Migrations, and instead just need your DbContext model created exactly as it is in your context class at first run, then you can use:

     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
     {
          using (var serviceScope = app.ApplicationServices.GetService().CreateScope())
          {
                var context = serviceScope.ServiceProvider.GetRequiredService();
                context.Database.EnsureCreated();
          }
    
          ...
    

    Instead.

    If you need to delete your database prior to making sure it's created, call:

                context.Database.EnsureDeleted();
    

    Just before you call EnsureCreated()

    Adapted from: http://docs.identityserver.io/en/latest/quickstarts/7_entity_framework.html?highlight=entity

提交回复
热议问题