ASP - Core Migrate EF Core SQL DB on Startup

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

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

    public static class EnsureMigration
    {
        public static void EnsureMigrationOfContext(this IApplicationBuilder app) where T:DbContext
        {
            var context = app.ApplicationServices.GetService();
            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();
    

提交回复
热议问题