Advertisement
Advanced .NET, Entity Framework Core & Data Access

How do EF Core migrations work, and what is the recommended workflow for applying them safely in production?

Short answer

`dotnet ef migrations add ` compares your current model against the last migration's snapshot and generates a new migration class (with Up/Down methods describing the schema change), which `dotnet ef database update` (or Migrate() called programmatically) then applies.

Save .NET mock interview
Advertisement
AModel answer
`dotnet ef migrations add <Name>` compares your current model against the last migration's snapshot and generates a new migration class (with Up/Down methods describing the schema change), which `dotnet ef database update` (or Migrate() called programmatically) then applies. For production, the recommended safe workflow separates migration generation (done during development, reviewed in code review like any other code) from migration application (run as a distinct, monitored deployment step, ideally with a database backup taken immediately before, rather than calling context.Database.Migrate() automatically on every application startup, which risks concurrent migration attempts from multiple app instances).
dotnet ef migrations add AddProductDiscountColumn
# Review the generated Up()/Down() methods in the migration file before committing

# Production: apply as a distinct pipeline step, not on every app startup
dotnet ef database update --connection "$PROD_CONNECTION_STRING"
Real-world example
A team learns the hard way after multiple simultaneously-starting container replicas all tried to run Database.Migrate() at once, causing a migration lock conflict -- they switch to running migrations as a single, separate pipeline step before deploying application instances.
Likely follow-ups
  • Why is calling Database.Migrate() on every app startup risky in a scaled-out deployment?
  • How do you generate a SQL script from migrations for DBA review instead of applying directly?
Related topics