这可能是一个愚蠢的问题,但 EF Core 似乎没有 Get-Migrations 命令。是无论如何都被更换了还是微软只是决定不需要它?
看来您是对的:Get-Migrations 似乎在 Entity Framework Core 中不可用。
作为替代方案,也许您可以使用
__EFMigrationsHistory
:
https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/history-table
默认情况下,EF Core 会跟踪已应用的迁移 通过将它们记录在名为的表中来存储到数据库 __EFMigrations历史记录。
与.Net Framework中的EF不同,您仍然可以通过命令
get-migration -context <your_context>
获取迁移列表。此命令显示您拥有的所有迁移,即使它已应用于数据库。请记住在进行迁移之前设置环境。
我不知道它是什么时候添加的,但 EF Core 现在确实有一个
Get-Migration
cmdlet。 请注意,所有 PowerShell cmdlet 都是单数,而不是复数(即 Get-Migration
,而不是 Get-Migrations)。
列出所有迁移,并显示它们是否已应用到数据库:
Get-Migration `
-StartupProject {Visual Studio project name containing app settings or config} `
-Project {Visual Studio project name containing DbContext}
-Context {DbContext name}
其中数据库是由启动项目 appsettings.json 或配置文件中的连接字符串指定的数据库。
示例:
(如果重复使用代码,请将
MyProject
、MyProject.Data
和 MyDbContext
替换为适当的名称)
列出所有迁移,以及它们是否已应用于数据库:
Get-Migration -StartupProject MyProject -Project MyProject.Data -Context MyDbContext
这将返回类似于以下内容的结果:
id name safeName applied
-- ---- -------- -------
20240325035415_CreateDatabase CreateDatabase CreateDatabase True
20240325041130_ExtendUserTable ExtendUserTable ExtendUserTable True
20240405234332_UpdateUserTypeId UpdateUserTypeId UpdateUserTypeId False
20240414092224_RemoveUserTypeTable RemoveUserTypeTable RemoveUserTypeTable False
要获取应用于数据库的最新迁移:
Get-Migration -StartupProject MyProject -Project MyProject.Data -Context MyDbContext |
Where-Object { $_.applied } |
Sort-Object id -Descending |
Select-Object -First 1
对于上面示例中的数据库,这将返回以下结果:
id name safeName applied
-- ---- -------- -------
20240325041130_ExtendUserTable ExtendUserTable ExtendUserTable True
列出尚未应用到数据库的迁移:
Get-Migration -StartupProject MyProject -Project MyProject.Data -Context MyDbContext |
Where-Object { -not $_.applied } |
Sort-Object id
对于上面示例中的数据库,这将返回以下结果:
id name safeName applied
-- ---- -------- -------
20240405234332_UpdateUserTypeId UpdateUserTypeId UpdateUserTypeId False
20240414092224_RemoveUserTypeTable RemoveUserTypeTable RemoveUserTypeTable False