Migrations

1 min read
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

  1. Add a migration. When the entity model changes, you scaffold a new migration with the command on line 1 below, or Add-Migration MigrationName in 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.
  2. Review the migration. Review the generated migration code, to make sure it reflects the changes you intended.
  3. 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 __EFMigrationsHistory table in the database to track which migrations have already been applied.
bash
dotnet ef migrations add MigrationNamedotnet ef database update

Model 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