What is a migration in EF Core?
Quick Answer
A migration is a versioned, code-generated description of a schema change. When you change your entity model, dotnet ef migrations add <Name> diffs the model against the last migration and writes Up()/Down() methods. dotnet ef database update (or Migrate() / a SQL script) applies them, and EF records which have run in the __EFMigrationsHistory table.
A migration is EF's record of a schema change, in code. I change the model, run migrations add with a name, and EF diffs against the last snapshot and generates Up and Down methods — create table, add column, and so on. Then database update applies it and EF logs it in the __EFMigrationsHistory table so it won't run twice. In development I just run update; for production I generate an idempotent SQL script and run it through the deployment pipeline. The rules are: review the generated migration for data loss and renames, never edit one that's already been applied, and keep migrations backward-compatible if you want zero-downtime releases.
Workflow:
- Change the model (add a property, a table, an index).
dotnet ef migrations add AddOrderStatus— generates a migration class and updates the model snapshot.- Review the generated code — check for data loss (dropped columns), rename detection (EF sees drop+add, not rename), and long-running operations.
- Apply:
database updatein dev; in production preferdotnet ef migrations script(idempotent SQL) run through your deployment pipeline, orDbContext.Database.Migrate()at startup for simple apps.
Interview points: never edit an applied migration — add a new one; migrations should be additive/backward-compatible for zero-downtime deploys (expand-then-contract); the model snapshot must stay in source control; multiple developers adding migrations in parallel causes snapshot conflicts that must be resolved carefully.
dotnet ef migrations add AddOrderStatus
dotnet ef database update # apply in dev
# for production: generate a script to run through the pipeline
dotnet ef migrations script --idempotent --output migrate.sql