加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:44:38 所属栏目:百科 来源:网络整理
导读:我的ConfigureServices中有一些代码在运行迁移时失败: dotnet ef migrations list 我正在尝试添加证书但它无法找到该文件(它在整个项目启动时起作用).那么有办法做这样的事情: if (!CurrentEnvironment.IsMigration()) { doMyStuffThatFailsInMigration()}
我的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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读