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

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)

这样,我可以保留我的代码,但是在不运行迁移时仅执行它即可。

谢谢

Nik*_*lia 9

只需在 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)


Gar*_*ley 4

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

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.DatabaseGetMigrationsGetAppliedMigrations

  • 问题不在于迁移是否发生。它与运行时环境有关,即当前进程是正常托管还是应用迁移的 dotnet-ef 工具。 (3认同)