我使用EF 6.0为我的项目在c#手动迁移和更新。我在数据库上进行了大约5次迁移,但我意识到最后一次迁移很糟糕,我不想要它。我知道我可以回滚到以前的迁移,但是当我添加一个新的(固定的)迁移并运行Update-Database时,甚至应用了糟糕的迁移。

我试图回滚到以前的迁移,并删除迁移不良的文件。但是,当我尝试添加新的迁移时,我在更新数据库时得到错误,因为迁移文件已损坏(更具体地说,第一行代码将表A重命名为B,然后是下一行,EF正在尝试用名称A更新表-可能是一些EF错误)。

是否有一些查询,我可以运行,这将告诉EF类似“忘记上次迁移,就像它从来没有存在过,它是坏的”?类似于Remove-Migration。

Edit1 我找到了适合我的解决办法。将模型更改为良好状态并运行Add-Migration TheBadMigration -Force。这将重新构建最后一个未应用的迁移。

无论如何,这仍然没有完全回答最初的问题。如果我UpdateDatabase到坏的迁移,我没有找到好方法如何回滚和创建新的迁移,排除坏的一个。

谢谢


当前回答

我使用EF核心与ASP。NET Core V2.2.6。@Richard Logwood的回答很棒,它解决了我的问题,但我需要一个不同的语法。

所以,对于那些使用EF核心与ASP。NET Core V2.2.6 +…

而不是

Update-Database <Name of last good migration>

我不得不使用:

dotnet ef database update <Name of last good migration>

而不是

Remove-Migration

我不得不使用:

dotnet ef migrations remove

我不得不求助:

dotnet ef migrations --help


Usage: dotnet ef migrations [options] [command]

Options:
  -h|--help        Show help information
  -v|--verbose     Show verbose output.
  --no-color       Don't colorize output.
  --prefix-output  Prefix output with level.

Commands:
  add     Adds a new migration.
  list    Lists available migrations.
  remove  Removes the last migration.
  script  Generates a SQL script from migrations.

Use "migrations [command] --help" for more information about a command.

这让我的角色回到我的DB按预期工作的阶段,并从头开始。

其他回答

你有两个选择:

You can take the Down from the bad migration and put it in a new migration (you will also need to make the subsequent changes to the model). This is effectively rolling up to a better version. I use this option on things that have gone to multiple environments. The other option is to actually run Update-Database –TargetMigration: TheLastGoodMigration against your deployed database and then delete the migration from your solution. This is kinda the hulk smash alternative and requires this to be performed against any database deployed with the bad version. Note: to rescaffold the migration you can use Add-Migration [existingname] -Force. This will however overwrite your existing migration, so be sure to do this only if you have removed the existing migration from the database. This does the same thing as deleting the existing migration file and running add-migration I use this option while developing.

首先,通过这个命令更新你最后的完美迁移:

Update-Database –TargetMigration

例子:

Update-Database -20180906131107_xxxx_xxxx

然后手动删除未使用的迁移。

对于EF 6,如果你在开发中重新搭建了很多,这里有一个单行程序。只需更新vars,然后继续使用包管理器控制台中的向上箭头来冲洗和重复。

$lastGoodTarget = "OldTargetName"; $newTarget = "NewTargetName"; Update-Database -TargetMigration "$lastGoodTarget" -Verbose; Add-Migration "$newTarget" -Verbose -Force

你问为什么有这个必要?不确定这适用于EF6的哪个版本,但如果你的新迁移目标已经被应用,那么使用'-Force'在Add-Migration中重新脚手架,实际上不会重新脚手架,而是创建一个新文件(这是一件好事,因为你不想失去你的'Down')。如果有必要,上面的代码片段首先进行“向下”,然后-Force正常工作以重新脚手架。

确保你的项目文件中没有错误,即使在你的迁移文件中,我在我的上一个迁移文件中有一个错误,不允许我删除它。

你也可以使用

Remove-Migration -Force

这将恢复并删除最后应用的迁移