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

编程入门 行业动态 更新时间:2024-10-14 12:24:27
本文介绍了在 EF Core 中,如何检查是否需要迁移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

In my core project that contains code (standard 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 中,如何检查是否需要迁移?

本文发布于:2023-11-14 22:15:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588652.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:EF   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!