How to rollback more than one EF Core migration at time

ef-migrations entity-framework-core

Question

I'm using EF Core 2.2 as ORM in my C# project, I have 8 migrations and I'm wondering if I can rollback not just the last one but more than one in a single rollback.

Update 1:

In other words, if I have n migrations, I want to apply the n - 2 or n - 3, I need to apply the n - m migration and not only the last one as the Remove-Migration

My final goal is to create a Powershell script so I can use it like below:

RollbackTo [TagetProject] "TargetMigration"

The prowershell will take two arguments: the Target Project and the migration to restore.

1
0
8/9/2019 2:41:18 PM

Accepted Answer

The solution is to update the database back to the target migration desired:

dotnet ef database update "THE NAME OF THE TARGET MIGRATION"

Execute this Ef Core command multiple time until the desired migration:

dotnet ef migrations remove

And below my Powershell script:

param (
    [Parameter(Mandatory=$true)][string]$migration,
    [Parameter(Mandatory=$true)][int]$nbr_removes
 )

 dotnet ef database update $migration

 for($i=0; $i -lt $nbr_removes; $i++) {
    dotnet ef migrations remove
    echo 'revert changes'
 }

And we can use it like below:

.\rollback_to.ps1 2019081200218_AddScoreColumn 2
0
8/12/2019 10:48:17 AM

Popular Answer

After update-database you cannot undo it. But as workaround there are 2 ways:

1.Look at the migrations you applied, There are 2 methods in it, Up and Down. Copy Down method. Then add a migration, paste the part you copied. apply update-database. Do it for the migrations you want to undo.IMPORTANT: Do it starting from the last migration.

  1. The clearer way if you dont care removing the database. Drop the database. Then remove the migrations you dont want to apply (deleted migrations should be the last ones, otherwise you could get error). Apply update-database. You will get the database as you wanted. In your case: apply the migrations one by one from the beginning, until the one you wanted to apply finally.


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow