c# – ASP.NET:检查是否从迁移运行

我的ConfigureServices中有一些代码在运行迁移时失败:

dotnet ef migrations list

我正在尝试添加证书但它无法找到该文件(它在整个项目启动时起作用).那么有办法做这样的事情:

if (!CurrentEnvironment.IsMigration()) {
    doMyStuffThatFailsInMigration()
}

这样我可以保持我的代码不变,但只是在迁移中不运行它时执行它.

谢谢

最佳答案 我当前的解决方案是检测是否未发生迁移:

using System.Linq;
// app is of type IApplicationBuilder
// RegisteredDBContext is the DBContext I have dependency injected
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetService<RegisteredDBContext>();
            if (context.Database.GetPendingMigrations().Any())
            {
                var msg = "There are pending migrations application will not start. Make sure migrations are ran.";
                throw new InvalidProgramException(msg);
                // Instead of error throwing, other code could happen
            }
        }

这假定迁移已经同步到数据库.如果仅调用了EnsureDatabase,则此方法不起作用,因为迁移仍处于挂起状态.

context.Database上还有其他方法选项. GetMigrations和GetAppliedMigrations.

点赞