How to generate a EF core migration script to rollback database

Let's see how to generate a rollback SQL script by using the standard dotnet ef migrations script command

Introduction

In this very short post, I’d like to share a quick tip that I actually had some troubles to find elsewhere on the internet that was easy to understand !

The need is pretty simple : I updated a database in my “staging” environment on which I cannot directly use the dotnet ef migrations command because updates are done through migrations scripts. Then I needed to revert it back on a previous stage.

We’ll see that it is in fact very easy to generate the same kind of script to rollback one or many migrations as easily.

Command line at the rescue

As you may expect, the dotnet ef migrations script command line can help us generate the SQL script that will allow us to “rollback” one a several migrations. Without further ado, here is the command line you might use to generate such a script with the :

dotnet ef migrations script <from-this-migration> <to-this-migration>

This command is of course not dedicated to rolling back, it will only depends on the order of your parameters ! For example with this command :

dotnet ef migrations script ThirdMigration SecondMigration

You will generate the script to rollback from migration Third to migration Second, and that’s it !

One more detail

As you may already know, the migrations are created thanks to the automatically scaffold files that you generate with the command dotnet ef migrations add MigrationName. In those files you will find two method : Up() and Down(). The method Up() is used to generate the migrations script when you want to apply this migration and the method Down() is used when you want rollback this migration.

This means that for any reason, if you edit the Up() method in this file (be sure to know what you are doing before updating this scaffolded file), don’t forget to also update the Down() method or you will not rollback your custom changes if you come across the need of going back !

Conclusion

I hope this small tip will help some of you that come across this blog post and will avoid you to loose some time on such a simple need !

See you soon with the next post !