Migrations
On trails:EFCOREstep 4/8
The idea
Migrations are a way to evolve the database schema over time as the application’s data model changes, while preserving the existing data in the database. EF Core Migrations let you manage these schema changes through code.
The workflow
- Add a migration. When the entity model changes, you scaffold a new migration with the command on line 1 below, or
Add-Migration MigrationNamein the Package Manager Console. EF Core compares the current model with a snapshot of the previous model to work out the necessary schema changes. It generates C# code, in a migration file, that describes them: creating tables, adding columns, creating indexes. - Review the migration. Review the generated migration code, to make sure it reflects the changes you intended.
- Apply the migration. Apply it to the database with the command on line 2 below, or
Update-Database. It executes the schema changes against the target database. EF Core keeps a special__EFMigrationsHistorytable in the database to track which migrations have already been applied.
bash
dotnet ef migrations add MigrationNamedotnet ef database updateModel snapshots
EF Core maintains a “model snapshot” file, usually YourDbContextModelSnapshot.cs, that represents the current state of the model. It is the baseline for generating the next migration.
Sources
- Migrations Overview, EF Core, Microsoft Learn · accessed May 16, 2025