How to downgrade database using code-first migration

by Sachin Singh

Posted on Tuesday, 19 January 2021

Tags: downgrading database using code-first migration

If you have to maintain different versions of your application then you may need different versions of the database as well, For example, consider current version of your application in the market is version 3 and your team is working on the next version that is version 4 but some bugs were found in the previous version then to fixed those bugs you will need to check out the previous version and start looking for the bugs and fixing them as soon as possible but in all of these you will need to downgrade your database up to that version too.

Downgrading a database becomes very easy when you are working with code-first workflow because with this workflow we get something to track our database called migrations and with migrations we can easily bring our database to any version we want, please follow the diagram shown below to understand the migration .

Migration vs App version
Migration vs app version

As you can see in the diagram above, the last launched version of the application uses three migrations but the current version which is under development uses 5 migrations, so if any bug is found at version1 of the application then to fix it we will have to check out the older version of the application in the source repository and downgrade the database up to M3 (third migration).

To downgrade the database up to the desired version that is up to migration M3 we use the following code

 PM>  update-database -TargetMigration : M3

The TargetMigraion is a switch which is used to target the last migration up to which you want your database to downgrade.

When we run the above migration , Entity Frameworks looks at the database and revert the last two migration that is migration M4 and M5 , to revert these two migrations it runs the Down() method of these two migrations.

Now , when our database is in the right state we can now checkout the older version of application from repository and start working on it , we will not face any issue as our database and application both would be in sync with each other.

After fixing the bugs in older version we again checkout the latest version of application into the source repository and run the latest migration using the code shown below.

  PM>  update-database -TargetMigration : M5

In this way we can bring our database to the latest version again.