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

标签 c# .net-standard ef-core-2.1

我在 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 ,您可以追踪它是如何工作的。 If 获取程序集中定义的所有迁移,并通过查询数据库删除它找到的迁移。

关于c# - 在 EF Core 中,如何检查是否需要迁移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54356964/

相关文章:

c# - 强制程序员调用其 Base 中的方法

c# - 如何覆盖NHibernate的类映射Where子句?

c# - 寻求有关如何将 JS 代码与 View 解耦的建议

asp.net-core - Entity Framework Core 1.1 OnModelCreating 方法未被调用

c# - 跨平台解决方案中哪些项目需要引用 .Net 标准库

c# - HasDefaultValue 与从构造函数设置默认值

c# - 创建一个以数字开头的属性

c# - 如何将自定义 DLL 加载到 PowerShell 中

c# - 如何在聚合之前将值转换为 long ?

asp.net-core - 如何使用 EFCore Code First Migrations 指定复合主键