当我在VS2015中使用ASP运行PM> Remove-Migration -context BloggingContext时。NET Core项目使用EF Core我得到以下错误:

System.InvalidOperationException: The migration '20160703192724_MyFirstMigration' has already been applied to the database. Unapply it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.    at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.RemoveMigration(String projectDir, String rootNamespace, Boolean force) 
    at Microsoft.EntityFrameworkCore.Design.MigrationsOperations.RemoveMigration(String contextType, Boolean force) 
    at Microsoft.EntityFrameworkCore.Tools.Cli.MigrationsRemoveCommand.<>c__DisplayClass0_0.<Configure>b__0() 
    at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args) 
    at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args) 
 The migration '20160703192724_MyFirstMigration' has already been applied to the database. Unapply it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.

如何取消申请?我使用的是ASP的最新版本。NET Core 1.0, EF Core和VS2015更新3。


当前回答

在包管理器控制台:

- database就Your_Migration_You_Want_To_Revert_To

关于如何恢复迁移的更多选项和解释可以在这里看到

其他回答

因为我在搜索ef而不是ef core中的回滚迁移时被重定向到这个问题,所以我将这个答案添加到这个问题中,供所有想知道ef中相同问题的人使用。如果你正在使用ef,你可以使用以下命令回滚迁移:

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

基于问题:

Update-Database -Migration <previous-migration-name> -context BloggingContext

1.找到表“dbo”。_efmigrationshhistory”,然后删除要删除的迁移记录。 2. 在PM(包管理控制台)运行“remove-migration”。 对我有用。

要取消应用特定的迁移:

dotnet ef database update LastGoodMigrationName
or
PM> Update-Database -Migration LastGoodMigrationName

取消所有迁移:

dotnet ef database update 0
or
PM> Update-Database -Migration 0

删除上次迁移:

dotnet ef migrations remove
or
PM> Remove-Migration

删除所有迁移:

只需删除迁移文件夹。

删除最后几个迁移(不是全部):

没有一个命令可以删除一堆迁移,我们不能只删除这几个迁移和它们的*.designer.cs文件,因为我们需要保持快照文件的一致状态。我们需要逐个删除迁移(参见上面删除最后一次迁移)。

取消应用并删除上次迁移:

dotnet ef migrations remove --force
or
PM> Remove-Migration -Force

你需要知道的所有事情的总结

所有命令都将使用dotnet编写。

这个解决方案是为。net Core 3.1提供的,但是也应该与下一个版本兼容

删除迁移:

删除迁移将从项目中删除文件 只有当迁移没有应用到数据库时,才能删除该迁移 然而, 要删除上次创建的迁移:cd to_your_project然后dotnet ef migrations remove

注意:只有在您还没有执行dotnet ef数据库更新或在c#代码中调用database . migrate()时,删除迁移才有效,换句话说,只有在迁移还没有应用到您的数据库时才有效。

取消应用迁移(恢复迁移):

从数据库中删除不需要的更改 不从项目中删除迁移文件,但允许您在取消应用后将其删除 要恢复迁移,您可以: 创建一个新的迁移dotnet ef migrations add <your_changes>并应用它,这是微软推荐的。 或者,使用dotnet ef database update <your_migration_name_to_jump_back_to>将数据库更新为指定的迁移(基本上是取消应用或恢复未选择的迁移)

注意:如果要取消应用的迁移不包含已经在数据库中应用并正在使用的特定列或表,则该列或表将被删除,您的数据将丢失。

在恢复迁移之后,您可以删除不需要的迁移

要完全删除所有迁移并重新开始,请执行以下操作:

dotnet ef database update 0
dotnet ef migrations remove