ASP - Core Migrate EF Core SQL DB on Startup

后端 未结 11 943
故里飘歌
故里飘歌 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:25

    This is a slight correction to the previous answer which created an extension method. It fixes the error that is thrown the way it was written.

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace MyApp.Extensions
    {
        public static class IApplicationBuilderExtensions
        {
            public static void SyncMigrations(this IApplicationBuilder app) where T : DbContext
            {
                using (var serviceScope = app.ApplicationServices.GetRequiredService().CreateScope())
                {
                    var context = serviceScope.ServiceProvider.GetService();
                    context.Database.Migrate();
                }
            }
        }
    }
    

提交回复
热议问题