我的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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。