【问题标题】:ASP.NET: Check if run from migrationASP.NET:检查是否从迁移运行
【发布时间】:2025-12-10 08:20:03
【问题描述】:

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

dotnet ef migrations list

我正在尝试添加证书,但找不到文件(它在启动整个项目时有效)。那么有没有办法做这样的事情:

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

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

谢谢

【问题讨论】:

    标签: c# asp.net entity-framework asp.net-core entity-framework-migrations


    【解决方案1】:

    只需在 Main 方法中设置一个静态标志(dotnet-ef 工具不调用):

    public class Program
    {
        public static bool IsStartedWithMain { get; private set; }
    
        public static void Main(string[] args)
        {
            IsStartedWithMain = true;
            ...
        }
    }
    

    然后在需要的时候检查一下:

    internal static void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)
    {
        if (Program.IsStartedWithMain)
        {
            // do stuff which must not be run upon using the dotnet-ef tool
        }
    }
    

    【讨论】:

      【解决方案2】:

      我目前检测是否没有发生迁移的解决方案:

      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 上还有其他方法选项。 GetMigrationsGetAppliedMigrations

      【讨论】:

      • 问题不在于是否发生了迁移。这是关于运行时环境,即当前进程是正常托管还是应用迁移的 dotnet-ef 工具。