mor*_*tzg 6 c# asp.net entity-framework ef-migrations asp.net-core
我有一些ConfigureServices运行迁移时失败的代码:
dotnet ef migrations list
Run Code Online (Sandbox Code Playgroud)
我正在尝试添加证书,但找不到文件(在整体启动项目时可以使用)。有没有办法做这样的事情:
if (!CurrentEnvironment.IsMigration()) {
doMyStuffThatFailsInMigration()
}
Run Code Online (Sandbox Code Playgroud)
这样,我可以保留我的代码,但是在不运行迁移时仅执行它即可。
谢谢
只需在 Main 方法中设置一个静态标志(不会被 dotnet-ef 工具调用):
public class Program
{
public static bool IsStartedWithMain { get; private set; }
public static void Main(string[] args)
{
IsStartedWithMain = true;
...
}
}
Run Code Online (Sandbox Code Playgroud)
然后在需要时检查它:
internal static void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)
{
if (Program.IsStartedWithMain)
{
// do stuff which must not be run upon using the dotnet-ef tool
}
}
Run Code Online (Sandbox Code Playgroud)
我当前检测迁移是否未发生的解决方案:
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
}
}
Run Code Online (Sandbox Code Playgroud)
这假设迁移已经同步到数据库。如果仅EnsureDatabase被调用,则此方法不起作用,因为所有迁移仍处于待处理状态。
上还有其他方法选项context.Database。GetMigrations和GetAppliedMigrations。
| 归档时间: |
|
| 查看次数: |
561 次 |
| 最近记录: |