我正在使用.Net Core构建MVC应用程序,并且需要生成迁移脚本。
在EF6中,我运行了该命令:
update-database -script
但是当我尝试在 .NET Core 中执行同样的操作时,会抛出以下异常:
Update-Database:找不到与参数名称“script”匹配的参数。
你知道 EF Core 是否有相应的替代方法吗?
我正在使用.Net Core构建MVC应用程序,并且需要生成迁移脚本。
在EF6中,我运行了该命令:
update-database -script
但是当我尝试在 .NET Core 中执行同样的操作时,会抛出以下异常:
Update-Database:找不到与参数名称“script”匹配的参数。
你知道 EF Core 是否有相应的替代方法吗?
Script-Migration
如果您想批量脚本化所有迁移,只需像这样从包管理器控制台调用它即可。如果您只想脚本化自上次迁移以来的更改,可以像这样调用:
Script-Migration -From <PreviousMigration> -To <LastMigration>
记得查阅文档,该命令还有一些其他选项。
dotnet ef migrations script --help
Usage: dotnet ef migrations script [arguments] [options]
Arguments:
<FROM> The starting migration. Defaults to '0' (the initial database).
<TO> The ending migration. Defaults to the last migration.
Options:
-o|--output <FILE> The file to write the result to.
-i|--idempotent Generate a script that can be used on a database at any migration.
-c|--context <DBCONTEXT> The DbContext to use.
-p|--project <PROJECT> The project to use.
-s|--startup-project <PROJECT> The startup project to use.
--framework <FRAMEWORK> The target framework.
--configuration <CONFIGURATION> The configuration to use.
--runtime <RUNTIME_IDENTIFIER> The runtime to use.
--msbuildprojectextensionspath <PATH> The MSBuild project extensions path. Defaults to "obj".
--no-build Don't build the project. Only use this when the build is up-to-date.
-h|--help Show help information
-v|--verbose Show verbose output.
--no-color Don't colorize output.
--prefix-output Prefix output with level.
所以,你可以尝试一下
dotnet ef migrations script ver1 ver2
dotnet ef migrations script ver1 ver2 -o ./script.sql
这适用于 .Net Core 2.1
dotnet ef migrations script
而不是 dotnet ef dbcontext script
。 - somethingRandom您可以使用dotnet core cli生成脚本
dotnet ef migrations script
您还可以使用新的PowerShell命令out-file
将此内容写入文件。
dotnet ef migrations script | out-file ./script.sql
out-file
的新语法将是 --output ./script.sql
。 - Steve Lam你也可以通过反转Script-Migration的参数生成回滚迁移的脚本。例如,如果你有两个迁移文件BadLatestMigration和GoodPreviousMigration,你可以使用以下命令还原到GoodPreviousMigration。
Script-Migration BadLatestMigration GoodPreviousMigration
之后一定要运行 Remove-Migration 命令来删除错误的迁移文件
Remove-Migration
这适用于.Net Core 2.2.0
这也仅生成SQL。
Update-Database -script -TargetMigration TO -SourceMigration FROM
dotnet ef migrations script
Script-Migration
dotnet ef migrations script AddNewTables
Script-Migration AddNewTables
dotnet ef migrations script AddNewTables AddAuditTable
Script-Migration AddNewTables AddAuditTable