我使用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按预期工作的阶段,并从头开始。

你也可以使用

Remove-Migration -Force

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

从。net Core 2.2开始,TargetMigration似乎消失了:

get-help Update-Database

NAME
    Update-Database

SYNOPSIS
    Updates the database to a specified migration.


SYNTAX
    Update-Database [[-Migration] <String>] [-Context <String>] [-Project <String>] [-StartupProject <String>] [<CommonParameters>]


DESCRIPTION
    Updates the database to a specified migration.


RELATED LINKS
    Script-Migration
    about_EntityFrameworkCore 

REMARKS
    To see the examples, type: "get-help Update-Database -examples".
    For more information, type: "get-help Update-Database -detailed".
    For technical information, type: "get-help Update-Database -full".
    For online help, type: "get-help Update-Database -online"

这对我来说是可行的:

Update-Database -Migration 20180906131107_xxxx_xxxx

以及(无-迁移开关):

Update-Database 20180906131107_xxxx_xxxx

另外要注意的是,您不能在不使Model Snapshot失去同步的情况下干净地删除迁移文件夹。因此,如果你以一种艰难的方式学习到这一点,并最终在你知道应该有更改的地方进行空迁移,你可以运行(上一次迁移不需要开关):

Remove-migration

它将清理混乱并将您送回需要的位置,即使最后一个迁移文件夹是手动删除的。

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

Update-Database –TargetMigration

例子:

Update-Database -20180906131107_xxxx_xxxx

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

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