在 EF Core 中,如何检查是否需要迁移? [英] In EF Core, how to check whether a migration is needed or not?

查看:25
本文介绍了在 EF Core 中,如何检查是否需要迁移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Entity Framework Core in an Xamarin.iOS application.

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

In my core project that contains code (.netstandard 2.0) that is shared between the iOS application and other applications, I would like to know if a migration is needed so that I can perform some other operations as well.

这里是上下文:

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

       demoTapeDbContext.Database.Migrate();
   }
}

我发现最接近的是调用方法 GetPendingMigrationsAsync() 并检查挂起迁移的数量,但我不确定这是否是在实体框架中进行此类检查的最安全方法:

The closest I have found is calling the method GetPendingMigrationsAsync() and check the amount of pending migrations but I am unsure whether it is the safest way to do such check in Entity Framework:

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

       demoTapeDbContext.Database.Migrate();
   }
}

推荐答案

您应该使用 GetPendingMigrationsAsync 方法是正确的.来自 文档:

You are correct that the GetPendingMigrationsAsync method is what you should use. From the docs:

异步获取在程序集中定义但尚未应用于目标数据库的所有迁移.

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

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

If you look at the code, you can trace how it works. If gets all of the migrations defined in your assembly and removes the ones it finds by querying the database.

这篇关于在 EF Core 中,如何检查是否需要迁移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆