EF Core Migrations Workflow
Objective
A migration is a C# file that moves the database schema from one version to the next, generated by comparing your model with a snapshot of the previous one. The tooling is easy to run and easy to trust too much. EF Core generates what it can infer from the model difference, and what it infers is sometimes destructive: a rename looks like a drop and an add. A reliable workflow treats the generated migration as code to review, keeps the snapshot consistent across branches, and lets CI prove that the model and the migrations agree.
Use Cases
- Adding a column and getting a migration whose
UpandDownyou can read in a pull request. - Renaming a property without losing the data in its column.
- Backfilling a new
NOT NULLcolumn for existing rows as part of the same change. - Two developers adding migrations on two branches, and merging them without a broken snapshot.
- Failing the build when someone changes an entity and forgets to add a migration.
Deep Dive
What migrations add produces
bashdotnet ef migrations add AddOrderPriority --project Orders.Core --startup-project Host
Three files appear. The migration class has Up and Down. A Designer file
holds metadata. OrdersDbContextModelSnapshot.cs is a full description of the
model as of this migration. The next migrations add diffs your current model
against that snapshot, not against the live database, which is why the snapshot
must be committed and must always match the last migration.
csharppublic partial class AddOrderPriority : Migration
{
protected override void Up(MigrationBuilder migrationBuilder) =>
migrationBuilder.AddColumn<int>(
name: "priority", schema: "orders", table: "orders",
type: "integer", nullable: false, defaultValue: 0);
protected override void Down(MigrationBuilder migrationBuilder) =>
migrationBuilder.DropColumn(name: "priority", schema: "orders", table: "orders");
}The tool needs a way to build your context without running the application. If
the app host is not enough, give it an IDesignTimeDbContextFactory<T>.
Review the generated SQL
Read the migration, and read the SQL it will run, before merging:
bashdotnet ef migrations script PreviousMigration AddOrderPriority --idempotent
The most important thing to look for is a rename. EF Core compares the old and
new model and cannot know that Total became GrandTotal, so it emits a drop
and an add, and the data in the column is gone:
csharp// Generated: loses the data.
migrationBuilder.DropColumn(name: "total", schema: "orders", table: "orders");
migrationBuilder.AddColumn<decimal>(name: "grand_total", schema: "orders", table: "orders", ...);
// What you meant: edit the migration by hand.
migrationBuilder.RenameColumn(name: "total", schema: "orders", table: "orders", newName: "grand_total");Data changes belong in the migration
When a schema change needs existing rows to change too, add the SQL to the same migration so schema and data move together. For a new required column, add it as nullable, fill it, then make it required:
csharpmigrationBuilder.AddColumn<string>("status_text", "orders", "orders", nullable: true);
migrationBuilder.Sql("UPDATE orders.orders SET status_text = CASE status WHEN 0 THEN 'Placed' ELSE 'Closed' END");
migrationBuilder.AlterColumn<string>("status_text", "orders", "orders", nullable: false, oldNullable: true);Prefer UseSeeding and UseAsyncSeeding (EF Core 9 and later) for seed data over
HasData, because HasData bakes the rows into every future snapshot. Always
implement UseSeeding too: the EF tools and migration bundles call the
synchronous delegate even when your application uses the asynchronous one.
Branches and the snapshot
Two branches that each add a migration both edit the model snapshot, and a
migration also carries the model as it was at that point. If both are merged,
the later migration's snapshot does not include the other branch's changes, which
can corrupt later migrations. EF Core 10 and earlier do not record the latest
migration in the snapshot, so source control can merge it without any conflict
even though the migration trees diverged. EF Core 11 closes that gap: the snapshot
written by dotnet ef migrations add 11.0.0 now starts with a generated comment about merge conflicts and the line
public override string LastMigrationId => "20261112000107_Initial";, so two
branches that each add a migration change the same line and the merge stops with a
text conflict. That conflict is the warning you want, not something to resolve by
picking a side. The documented fix is to re-create your
migration on top of your teammate's:
bash# Before merging, while your branch is still coherent:
dotnet ef migrations remove # remove only YOUR migration, keep the model change
git merge main # bring in the other branch's migration and snapshot
dotnet ef migrations add AddOrderPriority # re-add it on top of the merged snapshotIf the merge already happened, do not run migrations remove: it restores the
model from the previous migration's metadata, which may lack the other branch's
changes. Return to a coherent pre-merge state with source control and follow the
steps above.
Let CI check the model
dotnet ef migrations has-pending-model-changes (EF Core 8 and later) checks
whether the model has changes that no migration captures yet, so a CI step can
catch a forgotten migration. context.Database.HasPendingModelChanges() does the
same check from code, for example in a unit test. Since EF Core 9, Migrate() also throws if there are pending model changes,
which catches the same mistake at startup in a test environment.
Defaults and output in EF Core 11
EF Core 11 adds a .config/dotnet-ef.json file so you stop repeating
--project, --startup-project and --context on every command. dotnet ef
walks up from the current directory and uses the first one it finds, and
relative paths resolve against the parent of .config. I put this file at the
repository root:
json{ "project": "src/App", "context": "Ctx" }Running dotnet ef dbcontext info from the root and from src/ both found the
project and the context without any option. Explicit command-line options still
win, per the EF Core tools reference,
which also lists startupProject, framework, configuration, runtime,
verbose, noColor and prefixOutput.
Two details that matter in scripts. migrations add and migrations remove
write nothing to stdout: Build started..., Done. and the removal messages all
go to stderr, so capture stderr if you want to log them. dbcontext info and
dbcontext script write their result to stdout and keep the build messages on
stderr. And dotnet ef migrations remove --offline (new in EF Core 11, cannot
be combined with --force) removed the last migration without connecting to the
database. It deletes the files and rewrites the snapshot, so it only makes sense
when the migration was never applied.
To see what else the 11.0.0 tool adds, I installed dotnet-ef 10.0.12 and 11.0.0
side by side and diffed the options in --help for each command. Only in 11.0.0:
database update <name> --add(with--output-dir,--namespaceand--json) creates a migration and applies it in one step. The help says "Create a new migration with the given name and apply it immediately", and the documentation says it compiles the migration with Roslyn at run time, for places such as containers where the project cannot be rebuilt, and still writes the files for source control. I ran it on the 11.0.0 GA tool with SQLite: for the first migration of a project it worked ("Migration ... was successfully created and applied"), but with an earlier migration already in the project it generated a migration that repeatsCreateTablefor the whole model and failed withSQLite Error 1: 'table "Customers" already exists', leaving the broken migration file behind (undo withmigrations remove --force). Until that is fixed, usemigrations addthendatabase update, which produced the expectedAddColumn.--connectiononmigrations removeand ondatabase drop, so they no longer need a connection string in the context.--fileand--startup-fileon every command, as the file-based app equivalents of--projectand--startup-project.
One thing the documentation lists as new in 11 was already there: -c "*", which
runs migrations list, migrations script, database update or database drop for
every context, is in the --help of 10.0.12, so you do not need to upgrade the tool
for it. The Package Manager Console -NoBuild switch for Add-Migration and
Update-Database is documentation only, since there is no PMC here. The dotnet ef
CLI already had --no-build in both versions.
A related model option: HasOne(...).HasForeignKey(...).IsConstrained(false)
keeps the relationship in the model but leaves the foreign key constraint out of
the schema. On SQLite the generated script for an Item.ParentId relationship
had the column and CREATE INDEX "IX_Items_ParentId", but no FOREIGN KEY.
ExcludeForeignKeyFromMigrations() gives the same script, and the two are not
equivalent for queries, which join-pruning-and-foreign-keys-without-constraints
shows with real rows.
Trade-offs
- Auto-generated does not mean correct. Renames, column type changes that need a conversion, and splitting a table all need a hand-edited migration. Reviewing only the C# is not enough for a type change, so read the SQL.
Downis rarely exercised. ADownthat drops a column cannot bring back the data, so for production, a corrective forward migration is usually safer than reverting.- Editing an applied migration breaks other environments. Once a migration has run anywhere shared, changing it in place leaves databases in different states with the same migration id. Add a new migration instead.
- The snapshot is a single point of conflict. Many people adding migrations in a short window means regenerating often. Small, frequent merges reduce it.
HasDatais convenient and heavy. It stores every seed row in the snapshot, so changing one row generates a diff, and large seeds slow tooling. Use it only for small reference data that truly never changes.