当我在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。


当前回答

要恢复所有应用到DB的迁移,只需运行:

update-database 0

在migration目录中有可见的迁移文件时,应该多次运行Remove-Migration。该命令删除最近一次迁移,同时更新快照。

其他回答

首先执行以下命令:

PM>update-database -migration:0

然后运行这个:

PM>remove_migration

完成

一般来说,如果您正在使用Package Manager Console,删除特定迁移的正确方法是引用迁移的名称

Update-Database -Migration {Name of Migration} -Context {context}

另一种删除你根据文档应用的最后一个迁移的方法是使用命令:

dotnet ef migrations remove

这个命令应该从解决方案目录中的开发人员命令提示符(如何打开命令提示符)执行。

例如,如果你的应用程序名为“application”,在文件夹c:\Projects中。那么你的路径应该是:

C:\Projects\Application

移除迁移

如果上次迁移没有应用到数据库,则可以删除该迁移。使用下面的remove命令删除最后创建的迁移文件并恢复模型快照。

包管理控制台

点> remove-migration

CLI> dotnet ef迁移删除

上面的命令将删除最后一次迁移,并将模型快照恢复到前一次迁移。请注意,如果迁移已经应用到数据库,那么它将抛出以下异常。

迁移已经应用到数据库。恢复并重试。如果迁移已经应用到其他数据库,请考虑使用新的迁移恢复其更改。

恢复迁移

假设您更改了域类,并使用add-migration命令创建了名为MySecondMigration的第二次迁移,并使用Update命令将此迁移应用到数据库。但是,由于某种原因,您希望将数据库恢复到以前的状态。在这种情况下,使用update-database命令将数据库恢复到指定的先前迁移快照。

包管理控制台

更新数据库MyFirstMigration

CLI

. net ef数据库更新MyFirstMigration。

上面的命令将根据名为MyFirstMigration的迁移恢复数据库,并删除应用于名为MySecondMigration的第二次迁移的所有更改。这也将从数据库中的__efmigrationhistory表中删除MySecondMigration条目。

注意:这不会删除与MySecondMigration相关的迁移文件。使用remove命令将它们从项目中删除。

为了在EF Core 1.0中取消迁移,使用以下命令:

dotnet ef database update {migration_name}

使用您希望保留更改的迁移的迁移名称。可以使用以下命令找到迁移的名称列表:

dotnet ef migrations list

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

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

基于问题:

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