Covers the EF Core migrations workflow: migrations add, script and update, the Up/Down methods and Designer file, the ModelSnapshot, the __EFMigrationsHistory table, idempotent scripts and resolving migration conflicts between branches.
A migration is a C# class with Up() and Down() methods that move the schema from one model version to the next.
dotnet ef migrations add AddOrderStatus compares your current model with the ModelSnapshot (a C# file describing the model as of the last migration) and writes the difference.dotnet ef migrations script --idempotent produces reviewed SQL for production; dotnet ef database update applies it locally.__EFMigrationsHistory.In a team, two branches that both add migrations conflict in the snapshot: remove yours, merge, and re-add it. Never edit a migration that has been applied anywhere shared. The trade-off: migrations give versioned, repeatable schema changes, but the generated SQL still needs a human review.
"Migrations are how EF Core versions the database schema alongside the code. When I change the model, say I add a
Statuscolumn, I rundotnet ef migrations add AddOrderStatus. EF Core builds the current model, compares it with the model snapshot, which is a generated C# file describing the model as it was after the last migration, and writes a migration class with anUpmethod that adds the column and aDownmethod that removes it. It also updates the snapshot. All three files go into source control.To apply it locally I run
dotnet ef database update. For shared environments I generate a script withdotnet ef migrations script --idempotent, which wraps each migration in a check against the__EFMigrationsHistorytable, so the same script can run against any database version. That script is reviewed and run by the pipeline, not by the app at start-up.The team problem is merge conflicts. If two developers both add a migration on separate branches, each has a valid migration, but the snapshot conflicts. The fix is: whoever merges second removes their migration with
dotnet ef migrations remove, merges main, and adds it again, so it is generated on top of the other one. The mistake I see is editing a migration that has already been applied to a shared database, which means environments drift silently. The rule is simple: applied migrations are immutable; corrections are new migrations."
| Command | What it does |
|---|---|
dotnet ef migrations add <Name> |
Writes <timestamp>_<Name>.cs, .Designer.cs, updates ModelSnapshot.cs |
dotnet ef migrations remove |
Removes the last unapplied migration and reverts the snapshot |
dotnet ef migrations list |
Lists migrations and whether each is applied |
dotnet ef database update [<Target>] |
Applies (or rolls back to) a migration |
dotnet ef migrations script --idempotent |
SQL script safe to run against any version |
dotnet ef migrations bundle |
Self-contained executable that applies migrations |
dotnet ef migrations has-pending-model-changes |
Fails if the model changed without a migration (EF Core 8+) |
| File | Content |
|---|---|
20261119_AddOrderStatus.cs |
Up() and Down() using MigrationBuilder (AddColumn, CreateIndex, Sql) |
.Designer.cs |
Model snapshot as of this migration (used for Down and scripting) |
ShopDbContextModelSnapshot.cs |
Latest model; the baseline for the next add |
We added dotnet ef migrations has-pending-model-changes as a CI step after [two releases] shipped model changes with no migration. Since then the build fails within a minute instead of the deployment failing at night.
Checks that the candidate can use migrations safely in a team and knows how they reach production.
Green flags
Red flags
current model (from DbContext) ModelSnapshot.cs (last migration)
\ /
\ /
▼ ▼
IMigrationsModelDiffer → list of MigrationOperations
│
▼
C# migration code generator → Up()/Down()
The differ only sees two models. It cannot know intent, which is why a rename can show up as drop + add.
Migrate() or database update reads __EFMigrationsHistory, finds migrations not yet applied, runs each one's SQL (each in its own transaction on SQL Server, unless it contains statements that can't run in one), and inserts a history row. Since EF Core 9, Migrate() acquires a database-wide lock so two instances can't migrate at once, and it throws if the model has changes that no migration covers.
IF NOT EXISTS (SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20261119_AddOrderStatus')
BEGIN
ALTER TABLE [Orders] ADD [Status] int NOT NULL DEFAULT 0;
END;
This lets one artefact upgrade dev, test and production regardless of where each is.
main: M1 ─ M2 ──────────────── M3(A)
branch A: └─ M3(A) ───────┘
branch B: └─ M3(B) → conflict in snapshot → remove, merge, re-add as M4(B)
Migrations are ordered by their timestamp id; re-adding gives B a later id.
dotnet ef builds your startup project and gets the context from the host (CreateHostBuilder/WebApplication) or an IDesignTimeDbContextFactory<T>. Keep start-up code free of side effects (like seeding) so the tools don't trigger them.
migrations add, and read the three files.remove and re-add.dotnet ef migrations has-pending-model-changes to a CI workflow and make it fail.A typical generated migration, plus a hand-added data step.
namespace Shop.Infrastructure.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
public partial class AddOrderStatus : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "Status",
table: "Orders",
type: "int",
nullable: false,
defaultValue: 0);
// Hand-written data step: generated code never does this for you
migrationBuilder.Sql("UPDATE [Orders] SET [Status] = 2 WHERE [ShippedAt] IS NOT NULL;");
migrationBuilder.CreateIndex(
name: "IX_Orders_Status",
table: "Orders",
column: "Status");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(name: "IX_Orders_Status", table: "Orders");
migrationBuilder.DropColumn(name: "Status", table: "Orders");
}
}
dotnet ef migrations add AddOrderStatus --project src/Shop.Infrastructure --startup-project src/Shop.Api
dotnet ef migrations script --idempotent --output artifacts/migrate.sql
dotnet ef migrations has-pending-model-changes # CI gate
dotnet ef migrations remove.Database.Migrate() at start-up in production. Why it is wrong: since EF Core 9 the migration lock stops two instances corrupting the schema, but the other instances still wait on the lock during start-up, health probes can time out, the app identity needs DDL rights it otherwise shouldn't have, and a failed migration leaves every instance unable to start. Instead: run a reviewed script or bundle as a separate pipeline step with its own identity.Migrations are code that runs once against production data, so they deserve the strictest review in the repository. The senior setup: migrations generated by developers, an idempotent script or bundle produced by CI, has-pending-model-changes as a gate, the script applied first to a staging copy of production (a restored backup or an Azure SQL database copy) to measure duration and locking, then applied by the pipeline with a least-privilege identity separate from the app's.
Three more habits: keep each migration small and backwards-compatible so the previous app version still runs against the new schema (that is what makes rollback a redeploy rather than a restore); know your rollback plan before you apply (forward fix, Down only if it loses no data, point-in-time restore as the last resort); and treat data migrations that touch personal information like any other change to personal data under the Privacy Act, with the script reviewed and the run logged. In a microservices estate each service owns its own schema and its own migration history; never let two services migrate the same tables.
| Apply method | When it fits | Cost | When not to |
|---|---|---|---|
database update |
Local development | None | Shared environments |
| Idempotent SQL script | Regulated or DBA-reviewed releases | Script review step | — |
| Migration bundle | Containers, pipelines without the SDK | Build an extra artefact | When DBAs need to read SQL |
Migrate() at start-up |
Demos, single-instance tools | Start-up waits, DDL rights for the app | Multi-instance production |
I generate migrations locally with dotnet ef migrations add, then make deployment a separate, reviewed step. The pipeline produces an artefact: either an idempotent SQL script (dotnet ef migrations script --idempotent) for a DBA to review, or a migration bundle (dotnet ef migrations bundle), a self-contained executable that applies pending migrations. That artefact runs once, before the new app version starts, with a dedicated deployment identity. I avoid Database.Migrate() at startup because several instances can race, the app needs DDL permissions it shouldn't have, and a failed migration turns into a crash loop.
dotnet ef migrations bundle builds a single executable (efbundle) that contains your compiled migrations and applies the pending ones to whatever connection string you pass (./efbundle --connection "..."). The target machine needs no .NET SDK, no source and no dotnet-ef tool; with --self-contained -r linux-x64 it does not even need the .NET runtime. It runs migrations idempotently against __EFMigrationsHistory, so it fits a CI/CD release stage or a Kubernetes job. Choose an idempotent SQL script (dotnet ef migrations script --idempotent) instead when a DBA must review and run the SQL, when change control requires the exact statements as an artefact, or when the pipeline cannot reach the database with an executable. Both are better than Database.Migrate() at app start-up.
Last updated 23 Nov 2026.