Sunday 15 May 2016

Entity Framework 7– Unapplying Migrations to Remove Migrations

In development environments accidents can happen. You could add a wrong migration and want to roll back. The option is there to remove the last migration. But if it is applied to the local db, then the changes in local db should be unapplied before removing the migration.

Let’s look at how to do this with EF 7, step by step.

The problem

Accidently view model entities added as tables to the local db.image

Last added migration has created the view model entities in database.image


This has happened because db context class got updated with unwanted namespace and property, while creating a view with Visual Studio.image

How to fix?

Remove the unwanted namespace and property from the db context class.image

Remove the last migration. But this is giving the below error.

dnx ef migrations remove

The migration '20160514193811_SessionTime' has already been applied to the database. Unapply it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.image

Option1: If the changes applied to other databases, other than local development db, the way to fix should be via a new migration correcting the issues. It is possible to remove the unwanted namespace and property from the db context class and then create a new migration, which will have drop statements to drop unwanted tables.image



Option2: If the changes are only in local DB, unapply changes to local db by, updating the database into last known good migration. image

dnx ef database update RemoveEventTimeimage

This will remove last migration changes from local db.image


But running is applying the unwanted migration again and remove is failing.image


This is because once migration instance created using command line the changes are getting reapplied again for the, latest migration, which is the unwanted migration. The attempt to remove that get failing.

To fix this comment the db context class constructor applying the migrations.image

Note: It is not a good implementation to have constructor calling Database.Migrate(). Better implementation would be having it as a separate method in the db context class and calling it explicitly, from startup.image


A discussion on the same can be found here, which is saying the implementation of Database.Migrate() in the constructor is awful, which is exactly the correct way to introduce bad coding Smile

Make sure after fixing the db context class, you have compiled the solution with a rebuild.image

With this fix to “awful” code, in db context Option 2, reverting the migration by unapplying and remove works fine.image



No comments:

Popular Posts