ASP - Core Migrate EF Core SQL DB on Startup

后端 未结 11 888
故里飘歌
故里飘歌 2020-12-01 02:32

Is it possible to have my ASP Core Web API ensure the DB is migrated to the latest migration using EF Core? I know this can be done through the command line, but I want to

相关标签:
11条回答
  • 2020-12-01 03:03

    Use below code to run migration at

    public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetService<YourContext`enter code here`>();
            context.Database.Migrate();
        }
    }
    
    0 讨论(0)
  • 2020-12-01 03:07

    You can use

    db.Database.EnsureCreated();
    

    to get your db up to date with your current model. If you want to enable migrations (If subsequent migrations are suspected), then use

    db.Database.Migrate();
    

    and put your subsequent migrations over time.

    0 讨论(0)
  • 2020-12-01 03:11

    Based on chintan310's answer, here is how I migrate the database. This ensures separation of database-related tasks into Program.cs:

        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);
    
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
    
                try
                {
                    var context = services.GetService<AppDbContext>();
                    context.Database.Migrate();
    
                    var seeder = scope.ServiceProvider.GetService<AppSeeder>();
                    seeder.Seed().Wait();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }
    
            host.Run();
        }
    
        private static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    
    0 讨论(0)
  • 2020-12-01 03:12

    This code works in .NET core 3.0

     using (var scope = app.ApplicationServices.CreateScope())
     {
         var dbContext = scope.ServiceProvider.GetService<T>();
         dbContext.Database.Migrate();
     }
    
    0 讨论(0)
  • 2020-12-01 03:16

    Based on the answer of @steamrolla I would propose the following improvement:

    public static class EnsureMigration
    {
        public static void EnsureMigrationOfContext<T>(this IApplicationBuilder app) where T:DbContext
        {
            var context = app.ApplicationServices.GetService<T>();
            context.Database.Migrate();
        }
    }
    

    With this you can also ensure the migration of different contexts, e.g. if you have a Identity database.

    Usage:

    app.EnsureMigrationOfContext<context>();
    
    0 讨论(0)
  • 2020-12-01 03:17

    I did this to migrate programmatically with EF Core 2.1.2 & SQL Server, based on previous answers here and bailando bailando's answer on "How and where to call Database.EnsureCreated and Database.Migrate?":

    Startup.cs

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.EntityFrameworkCore;
    
    namespace MyApp
    {
        public class Startup
        {
            // ... (only relevant code included) ...
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<MyAppContext>(options => 
                    options.UseSqlServer(Configuration.GetConnectionString("MyAppContext")));
                // ...
            }
    
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                using (var serviceScope = app.ApplicationServices.CreateScope())
                {
                    var context = serviceScope.ServiceProvider.GetService<MyAppContext>();
                    context.Database.Migrate();
                }
                // ...
            }
        }
    }
    

    The project using this code is available at Github.

    0 讨论(0)
提交回复
热议问题