ChatGPT解决这个技术问题 Extra ChatGPT

Entity Framework rollback and remove bad migration

I'm using EF 6.0 for my project in C# with manual migrations and updates. I have about 5 migrations on the database, but I realised that the last migration was bad and I don't want it. I know that I can rollback to a previous migration, but when I add a new (fixed) migration and run Update-Database, even the bad migration is applied.

I was trying to rollback to the previous migration and delete the file with bad migration. But then, when I try to add new migration, I get error when updating database, because the migration file is corrupted (more specifically, first line of code rename the table A to B and is next lines, EF is trying to update table with name A - maybe it is some EF bug).

Is there some query I can run, which would tell EF something like "Forget last migration like it never existed, it was bad"? Something like Remove-Migration.

Edit1 I found solution suited for me. Changing model to the good state and run Add-Migration TheBadMigration -Force. This will re-scaffold the last, not applied migration.

Anyway, this still not answer the original question completely. If I UpdateDatabase to the bad migration, I did not found good way how to rollback and create new migration, excluding the bad one.

Thanks

I had to restart visual studio and then it started working properly. This has happened a couple of times to me already, always after messing around with migrations without actually updating database, so there's something strange going on with the tooling there.

N
Not loved

You have 2 options:

You can take the Down from the bad migration and put it in a new migration (you will also need to make the subsequent changes to the model). This is effectively rolling up to a better version. I use this option on things that have gone to multiple environments.

The other option is to actually run Update-Database –TargetMigration: TheLastGoodMigration against your deployed database and then delete the migration from your solution. This is kinda the hulk smash alternative and requires this to be performed against any database deployed with the bad version. Note: to rescaffold the migration you can use Add-Migration [existingname] -Force. This will however overwrite your existing migration, so be sure to do this only if you have removed the existing migration from the database. This does the same thing as deleting the existing migration file and running add-migration I use this option while developing.


The hulk smash option does not work. I did not yet applied the bad migration to the database. I tried, but it was not working, because the table names I specified in original question. The first option I don't like much, because it looks like I would have to change code of the migration. If I do it poorly, I can broke it all down.
If you havent yet applied the bad migration theres nothing stopping you either deleting it and rescaffolding or correcting the broken migration.
The 'hulk smash' is the answer, it works for me when developing and I want to add something to the migration I missed. I think the reasons it didn't work for Martin are unrelated (or probably related to changing the database schema manually)
@BenRethmeier as a general rule I use the hulk smash option only while I'm developing. In prod I always create a new migration to correct the issue. The reason is that you need manual intervention if you are downgrading the database. I don't like anything which needs manual intervention in prod.
HULK SMASH !!!!--- I tried being nice but EF was not playing - I reverted to last known - (Backed up migration files) Deleted, Added Migration - Force - Renamed to previous and copied the code.Update Database then added the second migration the same way - no errors - back to normal
D
David Sopko

As the question indicates this applies to a migration in a development type environment that has not yet been released.

This issue can be solved in these steps:

Restore your database to the last good migration. Delete the bad migration from your Entity Framework project. Generate a new migration and apply it to the database.

Note: Entity Framework and Entity Framework Core use slightly different command names

Step 1: Restore to a previous migration

If you haven't yet applied your migration you can skip this part. To restore your database schema to a previous point issue the Update-Database command with -TargetMigration option to specify the last good migration. For EFCore use Update-Database "Name-of-Migration"

If your entity framework code resides in a different project in your solution, you may need to use the '-Project' option or switch the default project in the package manager console.

Update-Database –TargetMigration: <name of last good migration>

For EFCore:

Update-Database <name of last good migration>

To get the name of the last good migration use the 'Get-Migrations' command to retrieve a list of the migration names that have been applied to your database, use 'Get-Migration' without the 's' if you are using EFCore.

PM> Get-Migrations
Retrieving migrations that have been applied to the target database.
201508242303096_Bad_Migration
201508211842590_The_Migration_applied_before_it
201508211440252_And_another

This list shows the most recent applied migrations first. Pick the migration that occurs in the list after the one you want to downgrade to, ie the one applied before the one you want to downgrade. Now issue an Update-Database.

Update-Database –TargetMigration: "<the migration applied before it>"

For EFCore:

Update-Database "<the migration applied before it>"

All migrations applied after the one specified will be down-graded in order starting with the latest migration applied first.

EF will reject the command if your downgrade might cause data loss. Use the '-Force' option to accept the data loss and allow the command to execute.

Step 2: Delete your migration from the project

If you are using Entity Framework Core you can use the 'remove-migration' command, for Entity Framework, delete the files of the unwanted migration in your EF project 'Migrations' folder manually. At this point, you are free to create a new migration and apply it to the database.

For EFCore:

remove-migration name_of_bad_migration

Step 3: Add your new migration

add-migration my_new_migration

Step 4: Apply your migration to the database

update-database

With EF Core it seems Get-Migrations has been removed.
Step2 ! - Very useful feature. As @KevinBurton mentioned. And then add-migration "new migration", update-database
Update-Database –migration: "" @David Sopko
After installing dotnet ef (EF Core 3.x) with dotnet tool install --global dotnet-ef I was able to list the migrations with dotnet-ef migrations list --project your-project-name.
we need to use remove-migration after step 2
R
Richard Logwood

For those using EF Core with ASP.NET Core v1.0.0 I had a similar problem and used the following commands to correct it (@DavidSopko's post pointed me in the right direction, but the details are slightly different for EF Core):

Update-Database <Name of last good migration>
Remove-Migration

For example, in my current development the command became

PM> Update-Database CreateInitialDatabase
Done.
PM> Remove-Migration
Done.
PM> 

The Remove-Migration will remove the last migration you applied. If you have a more complex scenario with multiple migrations to remove (I only had 2, the initial and the bad one), I suggest you test the steps in a dummy project.

There doesn't currently appear to be a Get-Migrations command in EF Core (v1.0.0) so you must look in your migrations folder and be familiar with what you have done. However, there is a nice help command:

PM> get-help entityframework

Refreshing dastabase in VS2015 SQL Server Object Explorer, all of my data was preserved and the migration that I wanted to revert was gone :)

Initially I tried Remove-Migration by itself and found the error command confusing:

System.InvalidOperationException: The migration '...' 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.

There are already suggestions on improving this wording, but I'd like the error to say something like this:

Run Update-Database (last good migration name) to revert the database schema back to to that state. This command will unapply all migrations that occurred after the migration specified to Update-Database. You may then run Remove-Migration (migration name to remove)

Output from the EF Core help command follows:

 PM> get-help entityframework
                     _/\__
               ---==/    \\
         ___  ___   |.    \|\
        | __|| __|  |  )   \\\
        | _| | _|   \_/ |  //|\\
        |___||_|       /   \\\/\\

TOPIC
    about_EntityFrameworkCore

SHORT DESCRIPTION
    Provides information about Entity Framework Core commands.

LONG DESCRIPTION
    This topic describes the Entity Framework Core commands. See https://docs.efproject.net for information on Entity Framework Core.

    The following Entity Framework cmdlets are included.

        Cmdlet                      Description
        --------------------------  ---------------------------------------------------
        Add-Migration               Adds a new migration.

        Remove-Migration            Removes the last migration.

        Scaffold-DbContext          Scaffolds a DbContext and entity type classes for a specified database.

        Script-Migration            Generates a SQL script from migrations.

        Update-Database             Updates the database to a specified migration.

        Use-DbContext               Sets the default DbContext to use.

SEE ALSO
    Add-Migration
    Remove-Migration
    Scaffold-DbContext
    Script-Migration
    Update-Database
    Use-DbContext

The command is "Get-Migration" NOT Get-MigrationS. Took me a miniute to figure that out! This was EntityFrameworkCore.Tools 5.07.
D
Daniël Tulp

You can also use

Remove-Migration -Force

This will revert and remove the last applied migration


G
Gert Arnold

I am using EF Core with ASP.NET Core V2.2.6. @Richard Logwood's answer was great and it solved my problem, but I needed a different syntax.

So, For those using EF Core with ASP.NET Core V2.2.6 +...

instead of

Update-Database <Name of last good migration>

I had to use:

dotnet ef database update <Name of last good migration>

And instead of

Remove-Migration

I had to use:

dotnet ef migrations remove

For --help i had to use :

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.

This let me role back to the stage where my DB worked as expected, and start from beginning.


EF Core has a Remove-Migration and remove commands. But if you are still on EF6, the Remove-Migration and remove commands are not available.
I am on EF Core and was able to use ONLY remove
if you are able to only use remove, then you must be using the dotnet CLI. Remove-Migration command is used on Package Management Console (PMC) on Visual Studios IDE.
A
Abdus Salam Azad

First, Update your last perfect migration via this command :

Update-Database –TargetMigration

Example:

Update-Database -20180906131107_xxxx_xxxx

And, then delete your unused migration manually.


it should be: Update-Database -TargetMigration 20180906131107_xxxx_xxxx
Update-Database 20180906131107_xxxx_xxxx (no hyphen) worked for me. No version of TargetMigration as a switch worked. These commands seem to be a moving target (i.e. change them in every version)?
S
Sum None

As of .NET Core 2.2, TargetMigration seems to be gone:

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"

So this works for me now:

Update-Database -Migration 20180906131107_xxxx_xxxx

As well as (no -Migration switch):

Update-Database 20180906131107_xxxx_xxxx

On an added note, you can no longer cleanly delete migration folders without putting your Model Snapshot out of sync. So if you learn this the hard way and wind up with an empty migration where you know there should be changes, you can run (no switches needed for the last migration):

Remove-migration

It will clean up the mess and put you back where you need to be, even though the last migration folder was deleted manually.


M
Michael Adamission

For EF 6 here's a one-liner if you're re-scaffolding a lot in development. Just update the vars and then keep using the up arrow in package manager console to rinse and repeat.

$lastGoodTarget = "OldTargetName"; $newTarget = "NewTargetName"; Update-Database -TargetMigration "$lastGoodTarget" -Verbose; Add-Migration "$newTarget" -Verbose -Force

Why is this necessary you ask? Not sure which versions of EF6 this applies but if your new migration target has already been applied then using '-Force' to re-scaffold in Add-Migration will not actually re-scaffold, but instead make a new file (this is a good thing though because you wouldn't want to lose your 'Down'). The above snippet does the 'Down' first if necessary then -Force works properly to re-scaffold.


D
Dharman

Be sure you don´t have error in project files, even in your migration files, I had an error in my last migration file and did not allow me remove it.