Mr. Mister
Mr. Mister

Reputation: 111

EF6 - Restoring previous database schema from __MigrationHistory

I read that __MigrationHistory table is used solely by EF.

I have a team working on the same project and we always have problems with the versioning files EF6 create in the application, and I have to delete them every time I create a migration and someone created another before me (the same happens with the other team members).

Is there a way to restore a previous version of a database schema using the data in __MigrationHistory table alone? Or is it not possible without the versioning files EF6 creates in the application?

Upvotes: 0

Views: 117

Answers (1)

Georg Patscheider
Georg Patscheider

Reputation: 9463

The clean way is to define the Down() method in the migration files correctly. Then you can go back to a certain version of the DB with the following command:

Update-Database -TargetMigration <Name of last migration to be applied>

Sometimes, you can also make EF happy by just adding an empty migration after the two migrations to be "merged". This empty migration is just there so EF can update its internal state and write it to _MigrationHistory correctly. This should get rid of the "Unable to update database to match the current model because there are pending changes and automatic migration is disabled." error.

To prevent the problems with migrations being created in parallel you have described, we always use the following process:

  • Only one team should have changes to the DB model checked out at any time
  • Before adding a new migration, always get latest version and apply Update-Database
  • Only now make the changes to the POCOs / ModelBuilder / DbContext
  • Add your migration with Add-Migration and also define the Down() method
  • Check in your changes before anyone else is allowed to make changes to the DB model
  • Track the migrations to be applied in an Excel file (for maintenance / support)

Note that model changes are tracked per DbContext, so maybe it is possible to split the DbContext into one separate context for each team. This would result one set of migrations per DbContext, i.e. team.

Upvotes: 2

Related Questions