How to Rollback Entity Framework Code First Migration

The code first approach to using the Entity Framework can be extremely helpful in creating a new database while staying entirely within your C# code base. If you’re more comfortable with creating plain old class objects (POCO) and then having those translated into SQL driven structures, code first is for you. That said, the process by which updates to the code base are pushed to the database (migrations) can be a bit frustrating to use at times. Not all SQL Server features are supported in a code first approach. In addition, migrating your structures in Azure has its own set of problems.

If you want to roll back to a previous migration due to an error in the current migration or wanting to rewind and start over, the following command can be used from the Package Manager Console in Visual Studio. This will rewind and undo any migrations between the current and the “migration-name” migration.

For example, if you have the following history of migrations in your project where the * indicates the current migration:

  • 201506042221067_RemoveColumn1
  • 201507031735200_AddColumn2
  • 201507044516322_CreateNewPersonTable
  • *20150731124746_SomeBrokenMigration

Use this command to roll back to the “AddColumn2” migration. Notice that the timestamp on the migration name is not included in the command.

The migration history will then look like:

  • 201506042221067_RemoveColumn1
  • *201507031735200_AddColumn2
  • 201507044516322_CreateNewPersonTable
  • 20150731124746_SomeBrokenMigration

Notice that the migrations which were rolled back were not deleted. The next time you perform an update-database command, the migrations will be re-executed. You will need to delete the migration from your project entirely if you want to avoid this.

Leave a Reply

Your email address will not be published. Required fields are marked *