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.
Last added migration has created the view model entities in database.
This has happened because db context class got updated with unwanted namespace and property, while creating a view with Visual Studio.
How to fix?
Remove the unwanted namespace and property from the db context class.
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.
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.
Option2: If the changes are only in local DB, unapply changes to local db by, updating the database into last known good migration.
dnx ef database update RemoveEventTime
This will remove last migration changes from local db.
But running is applying the unwanted migration again and remove is failing.
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.
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.
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
Make sure after fixing the db context class, you have compiled the solution with a rebuild.
With this fix to “awful” code, in db context Option 2, reverting the migration by unapplying and remove works fine.