423

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.

Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
nam
  • 21,967
  • 37
  • 158
  • 332

19 Answers19

504

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

Community
  • 1
  • 1
adem caglin
  • 22,700
  • 10
  • 58
  • 78
  • 8
    I'm still getting the same error. I first used `dotnet ef database update MyFirstMigration --context BloggingContext` that worked successfully. Then I ran `dotnet ef migrations remove --context BloggingContext` that gave me the same error message as in my post – nam Jul 05 '16 at 22:22
  • 31
    You'll need to update to the migration before `MyFirstMigration`. If that is the 1st migration (as the name implies) then you can use `dotnet ef database update 0` to revert(unapply) all migrations from the database. You should then be able to run `dotnet ef migrations remove`. – bvpb Jul 08 '16 at 00:15
  • 4
    Also it's worth noting that you should only use the name of the migration, excluding the date-prefix – Structed Oct 11 '17 at 16:03
  • 6
    Call `dotnet ef migrations remove` after this – Chamika Sandamal Sep 18 '18 at 05:36
  • 1
    Your second statement: "Then try to remove last migration" is not complete in this answer, please say exactly what you mean. remove the migration file? execute a command? ... – S.Serpooshan Dec 15 '18 at 06:23
  • Your mistake is to try to delete/remove the very same migration as the one to which you've upgraded your database last. You can't delete a migration that's still applied (i.e. current level of the database). You can only remove that migration after you've updated your database to the last migration BEFORE that one. Therefore, you must first update your database to (using the command he gave you) and then when you call "dotnet ef migrations remove" it implicitly deletes the LAST one, i.e. MyFirstMigration. – jeancallisti Aug 06 '19 at 09:34
  • @nam Its about "LastGoodMigration" not last migration. – ms2r Feb 12 '23 at 12:45
262

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
AlbertK
  • 11,841
  • 5
  • 40
  • 36
  • I keep seeing the word `unapply` all over these posts. It just hit me it's not a technical term, it's the word `un - apply` – Post Impatica Feb 11 '20 at 17:38
  • I wonder what is the method "down" used for ? – Pajri Aprilio Jan 24 '21 at 03:17
  • 2
    While viewing folder named `Migrations` in my Visual Studio IDE, and running above commands in my Package Manager Console, it would be super useful if this answer would state the expected results. For example, does removing effect the contents of the Migrations folder? That is, should the files resulting from an `Add-Migration` be removed, or do they remain and I need to remove them manually?? Thanks! – Adam Cox Feb 18 '21 at 14:58
  • dotnet ef migrations remove --force worked for me in ef core – Hamid Noahdi Feb 26 '21 at 08:27
  • 1
    @Pajri Aprilio When you remove a migration, the 'down' part lists the steps necessary to undo said migration. – RicardoArth Sep 22 '21 at 14:36
  • 1
    The command "Remove-Migration -Force" works for me. Thanks. – Thomas.Benz Sep 15 '22 at 14:49
178

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

dotnet ef database update 0
dotnet ef migrations remove
Ronald Ramos
  • 5,200
  • 2
  • 15
  • 12
  • 5
    But you don't want to remove all migrations. For example, you want to keep the default migration VS creates for identity (User Accounts) under Data\Migrations folder. – nam Nov 27 '16 at 18:53
  • 3
    It's good to know `dotnet ef database update 0`, but running `dotnet ef migrations remove` afterwards will remove default migration for Identity, which might not be desired. – kimbaudi Dec 01 '16 at 19:08
  • Thanks for the tip on `dotnet ef database update 0`! I hadn't seen this mentioned anywhere... – Tobias J Apr 24 '17 at 03:28
  • 8
    @nam "But you don't want to remove all migrations." But some of us do. Don't assume what I want :) – starmandeluxe Aug 15 '17 at 08:26
  • 4
    This didn't work for me. The first line was ok and remove all the migrations, on the second line I still get `The migration '20180618103514_InitialMigration' has already been applied to the database. Revert it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.` – Ido Ran Jun 18 '18 at 10:45
  • is there any way to do it in the run-time programmaticaly (e.g. using `dbContext.GetService()`)?? – Philipp Munin Jan 22 '19 at 20:45
  • Can I do that from the PM console? – Shimmy Weitzhandler May 28 '19 at 04:25
  • 1
    @ShimmyWeitzhandler Yes. https://stackoverflow.com/a/55323154/109941 – Jim G. Sep 09 '20 at 19:38
  • I was trying to remove the very first and sole migration I made and the '0' parameter helped :) – Abdelhakim Feb 14 '21 at 15:59
73

To revert the last applied migration you should:

  1. Revert migration from database:
    • PM> Update-Database <prior-migration-name>
    • PS/cmd> dotnet ef database update <prior-migration-name>
  2. If you call dbContext.Database.Migrate()/MigrateAsync() in Main/Startup: remove the latest migration file from project (or it will be reapplied again on next step)
  3. Update model snapshot:
    • PM> Remove-Migration
    • PS/cmd> dotnet ef migrations remove
Dmitry Polomoshnov
  • 5,106
  • 2
  • 24
  • 25
  • 4
    Thank you! This worked perfectly Fascinated that out of all the solutions no one ever mentioned the need for step 2. – Michael Kargl Aug 12 '18 at 10:24
  • 1
    Yeh, Nobody mentioned the step two.Thank you – Ajas Aju Oct 16 '18 at 10:55
  • not sure about the second step, in my case(latest VS2017) the migration file will be deleted automatically after calling `Remove-Migration` without problem. I'm not sure what you said "it will be reapplied again on next step"! – S.Serpooshan Dec 15 '18 at 06:32
  • @S.Serpooshan Indeed. I manually deleted it but when I ran Remove-Migration it complained about my previous migration having been applied to the database. But, it works. – MetalMikester Dec 17 '18 at 21:47
  • 1
    The second step I think is only necessary if you call `dbContext.Database.Migrate()` in your startup.cs – user3413723 Jan 29 '19 at 17:21
56

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.

Brad
  • 4,493
  • 2
  • 17
  • 24
  • You can call `Update-Database` from Package Management Console or call `dotnet ef database update` from the command prompt from the project directory. – kimbaudi Dec 01 '16 at 20:48
  • 10
    Just to clarify Brad's answer here - `` should be the name of the migration you want to *go back to* (i.e. probably the migration *before* the one you screwed up), not the name of the migration you want to undo. – Mark Amery May 01 '17 at 21:28
42

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

otherwise below 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

Amin Golmahalleh
  • 3,585
  • 2
  • 23
  • 36
36

Simply you can target a Migration by value

 Update-Database -Migration:0

Then go ahead and remove it

 Remove-Migration

NOTE this is for when you want to clear database.

John Nyingi
  • 951
  • 1
  • 16
  • 36
17

A summary of everything you need to know

All the commands will be written using dotnet.

This solution is provided for .net Core 3.1, but should be compatible with next versions as well

Removing migrations:

  • Removing a migration deletes the file from your project
  • 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

Omar El Hussein
  • 775
  • 8
  • 16
  • 1
    In your last note, I think you wanted to say: "if the destination migration you want to have after un-appling a migration, does not contain..." or "if the migration you want to un-apply to, does not contain" – Mike S. May 26 '21 at 11:15
11

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

Drewskis
  • 429
  • 6
  • 14
8

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!

Ole K
  • 754
  • 1
  • 9
  • 32
Raj
  • 200
  • 2
  • 6
  • 30
    This will not actually un-apply the migration, just make the framework "think" it has not been applied. Your database will be in an inconsistent state if you do this. – mark.monteiro Nov 22 '17 at 21:32
  • 1
    Manually editing the data in your __EFMigrationsHistory is terrible advice. Don't do it. That table is only meant to be used under-the-hood by the migration tools. If you start manually editing the data, a single mistake can create all kinds of crazy unexpected behavior in your project. It's a much better idea to use one of the other recommended solutions. – Joe Irby Dec 24 '18 at 12:18
  • We had a situation where a junior team member got confused with switching branches, and ended up deleting the migration manually from both (although it was still in the __EFMigrationsHistory table since it was already applied), so we lost the "down." This is what we ended up having to do, plus some manual reversals in SSMS. So don't do it - unless you have no other choice at this point. At least all he did was add a single new field. – Ella Nov 18 '19 at 21:01
8

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
Anastasios Selmani
  • 3,579
  • 3
  • 32
  • 48
  • 2
    The question was what to do if `dotnet ef migrations remove' returns an error "The migration has already been applied to the database" – Michael Freidgeim Mar 30 '18 at 08:58
8

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.

Dipendu Paul
  • 2,685
  • 1
  • 23
  • 20
8
dotnet ef database update <the-migration-you-want-to-recover>
dotnet ef migrations remove

Don't forget the remove-Call since this will remove the migration files for you and update the Snapshot-file.

Ruben Veldman
  • 440
  • 5
  • 9
Kheder
  • 203
  • 3
  • 9
8

As the question itself deals with a first migration this answer is for anyone who is here looking for way to revert their last migration since most answers do not cover the alternate scenarios (For most of us it's not our first migration and we cannot wipe the entire migration history).

These commands are for Package Manager Console.

Let's say you have the following migrations in your code:

  • 20220110_InitialMigration
  • 20200210_GoodMigration
  • 20200210_LastGoodMigration
  • 20200210_BadMigration
  • 20200210_BadMigrationAgain

If you have already applied the migration to the db like in the question

  1. Run:

    Update-Database -Migration <Last_Good_Migration_Name>

    Note: The name should be without date prefix. Eg: Update-Database -Migration LastGoodMigration

  2. Then to remove the bad migration run:

    Remove-Migration

    Note: Since we have two bad migrations run the Remove Migration command twice.

If you haven't applied the migration to the db

Just run:

Remove-Migration

In our case run the Remove Migration command twice.

Hope this helps someone.

UPDATE August 2023

If you have multiple db contexts add -Context Context_Name to each command. For example: Remove-Migration -Context MyDbContext

Charlie
  • 3,113
  • 3
  • 38
  • 60
7

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
SharpC
  • 6,974
  • 4
  • 45
  • 40
Rufus Lobo
  • 355
  • 3
  • 6
3

at first run the following command :

PM>update-database -migration:0

and then run this one :

PM>remove_migration

Finish

Rajan Sharma
  • 2,211
  • 3
  • 21
  • 33
Abbas Hadavandi
  • 111
  • 1
  • 2
2

Removing a Migration

You can remove the last migration if it is not applied to the database. Use the following remove commands to remove the last created migration files and revert the model snapshot.

Package Manager Console

PM> remove-migration

CLI> dotnet ef migrations remove

The above commands will remove the last migration and revert the model snapshot to the previous migration. Please note that if a migration is already applied to the database, then it will throw the following exception.

The migration has already been applied to the database. Revert it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.

Reverting a Migration

Suppose you changed your domain class and created the second migration named MySecondMigration using the add-migration command and applied this migration to the database using the Update command. But, for some reason, you want to revert the database to the previous state. In this case, use the update-database command to revert the database to the specified previous migration snapshot.

Package Manager Console

PM> Update-database MyFirstMigration

CLI

dotnet ef database update MyFirstMigration.

The above command will revert the database based on a migration named MyFirstMigration and remove all the changes applied for the second migration named MySecondMigration. This will also remove MySecondMigration entry from the __EFMigrationsHistory table in the database.

Note: This will not remove the migration files related to MySecondMigration. Use the remove commands to remove them from the project.

2

Because I've been redirected to this question for searching about roll back migration in ef not ef core, I'm adding this answer to the question for everybody who want to know about the same problem in ef. If you're using ef you can use the following command to roll back the migration:

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

Based on question:

Update-Database -Migration <previous-migration-name> -context BloggingContext
Majid M.
  • 4,467
  • 1
  • 11
  • 29
-1

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.

Atom
  • 1,433
  • 1
  • 7
  • 3