在 EF Core 中,如何检查是否需要迁移?

In EF Core, how to check whether a migration is needed or not?

我在 Xamarin.iOS 应用程序中使用 Entity Framework Core。

在包含 iOS 应用程序和其他应用程序之间共享的代码 (.netstandard 2.0) 的核心项目中,我想知道是否需要迁移以便我可以执行一些其他操作还有。

上下文如下:

public void Initialize()
{
   using (var dbContext = new MyDbContext(m_dbContextOptions))
   {
       --> bool isNeeded = demoTapeDbContext.Database.IsMigrationNeeded()

       demoTapeDbContext.Database.Migrate();
   }
}

我发现最接近的方法是调用方法 GetPendingMigrationsAsync() 并检查待处理迁移的数量,但我不确定这是否是进行此类检查的最安全方法 Entity Framework:

public async Task InitializeAsync()
{
   using (var dbContext = new MyDbContext(m_dbContextOptions))
   {
       bool isMigrationNeeded = (await demoTapeDbContext.Database.GetPendingMigrationsAsync()).Any();

       demoTapeDbContext.Database.Migrate();
   }
}

您说得对,GetPendingMigrationsAsync 方法是您应该使用的方法。来自 the docs:

Asynchronously gets all migrations that are defined in the assembly but haven't been applied to the target database.

如果您查看 the code,您可以了解它是如何工作的。如果获取程序集中定义的所有迁移,并通过查询数据库删除它找到的迁移。

我在DbInitializer中使用了以下代码:

public static class DbInitializer
{
    public static void Initialize(ApplicationDbContext context)
    {

        if(context.Database.GetPendingMigrations().Any()){
            context.Database.Migrate();
        }
        ...