Reputation: 20205
I am facing a weird problem with code first migrations in Entity Framework version 5. Sometimes Update-Database
fails due to pending changes but Add-Migration
command only produces migrations with database changes already contained in the last migrations and the database is up-to-date. Therefore I'd expect the new migration to be empty.
How does Add-Migration
detect what changes are due? It doesn't seem to use the database as a source.
Upvotes: 36
Views: 11248
Reputation: 5489
A snapshot of the database model is saved along with every migration in a .resx file. When you add a new migration, EF compares the current database model (which is generated from your model classes and settings from your DbModelBuilder) with the last migration and determines a changes between them.
The problem you are describing can occur if your migrations are out of sync. It happens to us if two developers make two independent migrations and these migrations are later merged back to the default branch.
Example:
Developer 1
Migration AddColumnA
Developer 2
Migration AddColumnB
Merged version
Migration AddColumnA - database snapshot includes columnA
Migration AddColumnB - database snapshot includes columnB but not columnA
If you add another migration, the changes are determined against migration AddColumnB, that doesn't contain information about columnA. A workaround for this problem is to generate dummy migration (with empty Up and Down methods) just to have the correct database model snapshot in the last migration.
Merged version
Migration AddColumnA - database snapshot includes columnA
Migration AddColumnB - database snapshot includes columnB but not columnA
Migration Dummy - database snapshot with columnA and columnB
Upvotes: 61