Ronaldo Lanhellas
Ronaldo Lanhellas

Reputation: 3356

Can't remove Database Migration with Ef Core

Well, I'm trying to revert a database migration that simple add a column, see:

 public partial class CreateColumnTypeCamera : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<string>(
                name: "type",
                table: "CAMERA",
                type: "varchar",
                nullable: false,
                defaultValue: "");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "type",
                table: "CAMERA");
        }
    }

After execute dotnet ef database update everything works fine and my database is updated. But I want to revert it, so I tried dotnet ef database update CreateColumnTypeCamera:

[ronaldo@localhost WebApi]$ dotnet ef database update CreateColumnTypeCamera
Done.

As you can see I got "Done", but nothing is reverted, the column was not dropped. If I try to remove my migration I got an error:

[ronaldo@localhost WebApi]$ dotnet ef migrations remove
The migration '20200329134024_CreateColumnTypeCamera' 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.

Edit 1:

I applied the "update" command to "LastGoodMigration" instead my bad migration, and everything works fine. But the error in remove continue, so I noted that is because of this line:

 if (Database.ProviderName != "Microsoft.EntityFrameworkCore.InMemory")
      {
        Database.Migrate();
      }

There is any way to fix it ? If I try to apply "ef remove" with this line I got the error showed above.

Upvotes: 3

Views: 8989

Answers (2)

Cristina Carrasco
Cristina Carrasco

Reputation: 713

You will need to run

update-database OneMigrationBeforeTheOneYouWantToRemove

Updating database to the previous migration of the one you want to remove. This will revert changes on the database and also remove the migration from _migrations table.

After that you can run:

Remove-Migration

which will remove the last migration, you can run it 'n' times until you reach the desire migration to remove.

Upvotes: 3

AlleXyS
AlleXyS

Reputation: 2598

go to database, table EF_migrations and remove the migration with specific id (table row), then you can remove the files from migrations folder. Don't forgot to update manually the tables which are affected by this migration.

Upvotes: 0

Related Questions