[c#] How to unapply a migration in ASP.NET Core with EF Core

When I run PM> Remove-Migration -context BloggingContext in VS2015 with an ASP.NET Core project using EF Core I get the following error:

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.

How can I unapply it? I'm using latest release of ASP.NET Core 1.0, EF Core, and VS2015 Update 3.

The answer is


You can do it with:

dotnet ef migrations remove

Warning

Take care not to remove any migrations which are already applied to production databases. Not doing so will prevent you from being able to revert it, and may break the assumptions made by subsequent migrations.


Use:

CLI

> dotnet ef database update <previous-migration-name>

Package Manager Console

PM> Update-Database <previous-migration-name>

Example:

PM> Update-Database MyInitialMigration

Then try to remove last migration.

Removing migration without database update doesn't work because you applied changes to database.

If using PMC, Try: PM> update-database 0 This will wipe the database and allow you to remove the Migration Snapshot on your Solution


To unapply a specific migration(s):

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

To unapply all migrations:

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

To remove last migration:

dotnet ef migrations remove
or
PM> Remove-Migration

To remove all migrations:

just remove Migrations folder.

To remove last few migrations (not all):

There is no a command to remove a bunch of migrations and we can't just remove these few migrations and their *.designer.cs files since we need to keep the snapshot file in the consistent state. We need to remove migrations one by one (see To remove last migration above).

To unapply and remove last migration:

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

In order to unapply a migration in EF Core 1.0 use the command:

dotnet ef database update {migration_name}

Use the migration name of the migration until which you would like to preserve your changes. The list of names of the migration can be found using:

dotnet ef migrations list


You can still use the Update-Database command.

Update-Database -Migration <migration name> -Context <context name>

However, judging by the name of your migration i'm assuming it's the first migration so that command may not work. You should be able to delete the entry from the __MigrationHistory table in your database and then run the Remove-Migration command again. You could also delete the migration file and just start again.


In general if you are using the Package Manager Console the right way to remove a specific Migration is by referencing the name of the migration

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

Another way to remove the last migration you have applied according to the docs is by using the command:

dotnet ef migrations remove

This command should be executed from the developer command prompt (how to open command prompt) inside your solution directory.

For example if your application is inside name "Application" and is in the folder c:\Projects. Then your path should be:

C:\Projects\Application

You should delete migration '20160703192724_MyFirstMigration' record from '_EFMigrationsHistory' table.

otherwise this command will remove migration and delete migrations folder:

PMC Command:

   > remove-migration -force

CLI Command:

   > dotnet ef migrations remove -f

Link About CLI Commands

Link About PMC Commands


Simply you can target a Migration by value

 Update-Database -Migration:0

Then go ahead and remove it

 Remove-Migration

Note: It might be troublesome later on, I used it as a last resort since non of the solutions provided above and others did not work in my case:

  1. Copy the code from the body of previous successful migration's down() method.
  2. Add a new migration using Add-Migration "migration-name"
  3. Paste the copied code from the down() method of previous migration to the new migration's Up() method:
    Up(){ //paste here }
  4. Run Update-Database
  5. Done, your changes from the previous migration should now have been reverted!

To completely remove all migrations and start all over again, do the following:

dotnet ef database update 0
dotnet ef migrations remove

To revert the last applied migration you should (package manager console commands):

  1. Revert migration from database: PM> Update-Database <prior-migration-name>
  2. Remove migration file from project (or it will be reapplied again on next step)
  3. Update model snapshot: PM> Remove-Migration

UPD: The second step seems to be not required in latest versions of Visual Studio (2017).


To "unapply" the most (recent?) migration after it has already been applied to the database:

  1. Open the SQL Server Object Explorer (View -> "SQL Server Object Explorer")
  2. Navigate to the database that is linked to your project by expanding the small triangles to the side.
  3. Expand "Tables"
  4. Find the table named "dbo._EFMigrationsHistory".
  5. Right click on it and select "View Data" to see the table entries in Visual Studio.
  6. Delete the row corresponding to your migration that you want to unapply (Say "yes" to the warning, if prompted).
  7. Run "dotnet ef migrations remove" again in the command window in the directory that has the project.json file. Alternatively, run "Remove-Migration" command in the package manager console.

Hope this helps and is applicable to any migration in the project... I tested this out only to the most recent migration...

Happy coding!


at first run the following command :

PM>update-database -migration:0

and then run this one :

PM>remove_migration

Finish


In Package Manager Console:

Update-Database Your_Migration_You_Want_To_Revert_To

More options and explanation on how to revert migrations can be seen here


1.find table "dbo._EFMigrationsHistory", then delete the migration record that you want to remove. 2. run "remove-migration" in PM(Package Manager Console). Works for me.


To revert all the migrations which are applied to DB simply run:

update-database 0

It should be followed with running Remove-Migration as many times as there are migration files visible in the Migration directory. The command deletes the latest migration and also updates the snapshot.


in Package Manager Console, just Type Remove-Migration And Press Enter. It automatically removes the migration.

Tools -> Nuget Package Manager -> Package Manager Console


More details and solutions here:

I don't understand why we are confusing things up here. So I'll write down a clear explanation, and what you have to notice.

All the commands will be written using dotnet.

This solution is provided for .net Core 3.1, but should be compatible with all other generations as well

Removing migrations:

  • Removing a migration deletes the file from your project (which should be clear for everyone)
  • Removing a migration can only be done, if the migration is not applied to the database yet
  • To remove last created migration: cd to_your_project then dotnet ef migrations remove

Note: Removing a migration works only, if you didn't execute yet dotnet ef database update or called in your c# code Database.Migrate(), in other words, only if the migration is not applied to your database yet.

Unapplying migrations (revert migrations):

  • Removes unwanted changes from the database
  • Does not delete the migration file from your project, but allows you to remove it after unapplying
  • To revert a migration, you can either:
    • Create a new migration dotnet ef migrations add <your_changes> and apply it, which is recommended by microsoft.
    • Or, update your database to a specified migration (which is basically unapplying or reverting the non chosen migrations) with dotnet ef database update <your_migration_name_to_jump_back_to>

Note: if the migration you want to unapply, does not contain a specific column or table, which are already in your database applied and being used, the column or table will be dropped, and your data will be lost.

After reverting the migration, you can remove your unwanted migration

Hopefully this helps someone!


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-core

dotnet ef not found in .NET Core 3 How to use Bootstrap 4 in ASP.NET Core ASP.NET Core - Swashbuckle not creating swagger.json file Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 EF Core add-migration Build Failed ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

Examples related to entity-framework-core

dotnet ef not found in .NET Core 3 How to update record using Entity Framework Core? Unable to create migrations after upgrading to ASP.NET Core 2.0 Error: the entity type requires a primary key Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver' auto create database in Entity Framework Core Entity Framework Core add unique constraint code-first How to unapply a migration in ASP.NET Core with EF Core The term "Add-Migration" is not recognized Auto-increment on partial primary key with Entity Framework Core

Examples related to .net-core

dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Assets file project.assets.json not found. Run a NuGet package restore Is ConfigurationManager.AppSettings available in .NET Core 2.0? How to update record using Entity Framework Core? Using app.config in .Net Core EF Core add-migration Build Failed Build .NET Core console application to output an EXE What is the difference between .NET Core and .NET Standard Class Library project types? Where is NuGet.Config file located in Visual Studio project?

Examples related to visual-studio-2015

How to download Visual Studio Community Edition 2015 (not 2017) The default XML namespace of the project must be the MSBuild XML namespace tsconfig.json: Build:No inputs were found in config file How to install Visual C++ Build tools? Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" How to unapply a migration in ASP.NET Core with EF Core The term "Add-Migration" is not recognized Visual Studio 2015 Update 3 Offline Installer (ISO) Getting "project" nuget configuration is invalid error ASP.NET 5 MVC: unable to connect to web server 'IIS Express'