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.
Add-Migration: Creates a new migration class as per specified name with the Up() and Down() methods. Update-Database: Executes the last migration file created by the Add-Migration command and applies changes to the database schema.
Migration is a way to keep the database schema in sync with the EF Core model by preserving data. As per the above figure, EF Core API builds the EF Core model from the domain (entity) classes and EF Core migrations will create or update the database schema based on the EF Core model.
Using multiple context types One way to create multiple migration sets is to use one DbContext type per provider. Specify the context type when adding new migrations. You don't need to specify the output directory for subsequent migrations since they are created as siblings to the last one.
The migrations feature in EF Core provides a way to incrementally update the database schema to keep it in sync with the application's data model while preserving existing data in the database.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With