它是一种检查当前在数据库上的迁移(版本)的方法

时间:2016-11-09 11:59:13

标签: .net entity-framework-core

我试图弄清楚是否有办法检查哪个迁移版本是最新的,已在数据库上运行。这可以知道某个数据库的状态。

我读过有关实体框架6的内容正在创建一个表来跟踪它。我没有尝试过,但我想知道是否有类似于实体框架的核心。

2 个答案:

答案 0 :(得分:5)

可以使用以下代码获取Entity Framework Core中的待定迁移列表:

var migrationsAssembly = db.GetService<IMigrationsAssembly>();
var historyRepository = db.GetService<IHistoryRepository>();

var all = migrationsAssembly.Migrations.Keys;
var applied = historyRepository.GetAppliedMigrations().Select(r => r.MigrationId);
var pending = all.Except(applied);

https://github.com/aspnet/EntityFramework/issues/6110#issuecomment-242220554

您需要包含几个使用语句:

using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

有一个类似于EF 6中的更正式API的公开问题:https://github.com/aspnet/EntityFramework/issues/577

答案 1 :(得分:3)

至少可以获得

  

在程序集中定义但尚未应用的迁移   到目标数据库。

source)通过DbMigrator方法getPendingMigrations()

如果您想要数据库的实际版本,实际上有一个包含__MigrationHistory列的迁移历史记录表MigrationId,它可以为您提供所需的内容。这是一篇展示如何使用它的文章:https://msdn.microsoft.com/en-us/data/dn456841.aspx