为 Entity Framework 6 C# 中的特定迁移获取 SQL 文件

Get SQL file for specific migration in Entity Framework 6 C#

在 Entity Framework 6 中,我需要获取特定迁移文件的 SQL 脚本并且我已经更新了数据库。我发现在 update-database 命令中我可以添加脚本参数以将迁移导出到 SQL,但我已经更新了数据库。我在 Entity Framework Core 中找到了一个名为 Script-Migration 的命令,它以脚本名称作为参数。 Entity framework中有没有类似的命令?

我也尝试了建议“Update database command”,但我得到一个空的 SQL 文件。

是的,您可以按如下方式生成 migration-SQL:

Update-Database -Script -SourceMigration: <pointFromWichYouWantToStartWithGeneration> -TargetMigration: <pointWhereToEndWithGeneration>

要为所有迁移创建脚本,请执行以下操作:

Update-Database -Script -SourceMigration: $InitialDatabase

它不会将更改应用到数据库,而是生成一个 SQL 脚本文件。因此,即使迁移已应用于数据库,您也可以生成 SQL 脚本。

在这里您可以找到更多关于它的信息 - Entity Framework Code First Migrations - Getting a SQL Script

Run the Update-Database command but this time specify the –Script flag so that changes are written to a script rather than applied. We’ll also specify a source and target migration to generate the script for.

如果要为迁移 N 生成 -Script,请指定 -SourceMigration N-1(之前的迁移)和 -TargetMigration N

如果您现在使用的是 .net 核心,请使用

Script-Migration -From <PreviousMigration> -To <LastMigration>

如果不执行上次迁移,可以运行

Script-Migration -From <PreviousMigration>

迁移名称前不要包含 date/times。 例如,如果数据库中的迁移名称是:20210209184835_add-parent-id-to-contract,那么 运行 包管理器中的以下内容

Script-Migration -From add-parent-id-to-contract

您可以从程序包管理器控制台运行执行以下命令。它将生成一个临时文件并在 VS 中打开它:

Script-Migration