The Analogy: The Renovation Log
A building that has been extended four times has two kinds of document. There are the current floor plans, which say what the building is today, and there is the renovation log: a numbered list of every alteration, in the order it was carried out, with the drawings for each one. The plans tell you where the walls are. The log tells you how to get from the building as it was to the building as it is.
You need the log because you cannot renovate a building by handing someone the finished plans. Real sites are occupied. Walls come down in a particular order, the water is off for one afternoon and not for a week, and the fire escape is added before the old stairs are removed rather than after. An alteration that would be trivial on an empty site becomes a sequence of careful steps on a live one.
EF Core migrations are that log. Each migration is a numbered, timestamped class with an Up describing the alteration and a Down undoing it, and every database records which migrations it has applied in a table called __EFMigrationsHistory. Your entity classes are the floor plans — the desired state — and the migration is the diff EF Core computed between the previous desired state and the new one.
The occupied-building problem is the whole reason this lesson exists. Splitting a Name column into FirstName and LastName is one line in your model and, on a running system with a previous version of the code still serving requests, three deployments: add the new columns, move the data, remove the old column. Get the order wrong and the site is down. The queries have to stay in step too — a column that no longer exists is a runtime error, and an index that no longer matches your WHERE clause is a table scan.
Syntax or Core Structure
Migrations need a design-time package and a global tool. After that the workflow is: change the model, generate a migration, read it, apply it.
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
# Change the model first, then diff it against the last snapshot.
dotnet ef migrations add AddOrders
# Apply everything not yet recorded in __EFMigrationsHistory.
dotnet ef database update
dotnet ef migrations list # what exists and what is pending
dotnet ef migrations remove # delete the last one - only if not applied
dotnet ef database update AddOrders # move to a specific migration, up or down
# For deployments where the application has no schema rights:
dotnet ef migrations script --idempotent --output migrate.sql
The generated class is ordinary C# you can read and edit before applying it (trimmed here for readability):
using Microsoft.EntityFrameworkCore.Migrations;
public partial class AddOrders : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Sku = table.Column<string>(maxLength: 20, nullable: false),
Quantity = table.Column<int>(nullable: false),
CustomerId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Customers_CustomerId",
column: x => x.CustomerId,
principalTable: "Customers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_CustomerId",
table: "Orders",
column: "CustomerId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(name: "Orders");
}
}
Output: (abridged - timestamps and wording vary by version)
Build started...
Build succeeded.
20260714093012_InitialCreate
20260721142255_AddOrders (Pending)
Three things in that class are worth noticing. Up and Down are symmetric, so dotnet ef database update InitialCreate can walk backwards. The migration references tables and columns by name as strings, not by your entity types, which is exactly right — a migration must keep describing the alteration it made even after you rename the C# property next year. And the index on CustomerId was added because a foreign key without an index makes every join and every cascade delete a scan; EF Core adds it by convention, and hand-written SQL usually forgets.
The --idempotent script is the option most teams end up standardising on. It wraps every migration in a check against __EFMigrationsHistory, so the same file can be run against a database at any version and applies only what is missing — which is what you want when a DBA runs it, or when the same script is applied to staging and then production.
Technical Depth: History, Snapshots and Safe Order
How EF Core knows what to apply
| Piece | Where it lives | Purpose |
|---|---|---|
| Migration class | Migrations/20260721142255_AddOrders.cs | The Up/Down alterations |
| Designer file | ..._AddOrders.Designer.cs | The model as of this migration |
| Model snapshot | Migrations/ShopContextModelSnapshot.cs | The current desired state |
| History table | __EFMigrationsHistory in the database | Which migrations this database has |
migrations add diffs your entity model against the snapshot file, not against the database. That is why deleting a migration file by hand breaks everything: the snapshot still describes the deleted state, so the next migration is generated as a diff from a state no migration produces. Use dotnet ef migrations remove, which updates the snapshot too.
The snapshot is also the file that conflicts on every merge when two people add migrations on separate branches. The fix is mechanical but must be done in order: rebase, delete your own migration with remove, take their snapshot, then regenerate yours on top. Merging the snapshot by hand produces a model that matches neither branch.
Read every generated migration before applying it
The generator is good but it cannot know your intent. Two cases in particular need a human:
- Renames are guessed as drop-and-add. Renaming
NametoFullNamein the model generatesDropColumnplusAddColumn, which deletes every value in that column. Replace it by hand withmigrationBuilder.RenameColumn(...), or useRenameTablefor a table. - Making a column required needs the data to cooperate.
AlterColumntonullable: falsefails on any existingNULL. The migration needs amigrationBuilder.Sql("UPDATE ... SET ... WHERE ... IS NULL")before the alter.
Data movement belongs in the migration as SQL: migrationBuilder.Sql("...") runs in the same transaction as the schema change. Do not open a DbContext inside a migration and call SaveChanges. That code compiles against today's entity classes, but the migration will still be run years from now when those classes have changed, and it will break or, worse, write the wrong columns.
Applying migrations at deployment time
| Approach | Good for | Risk |
|---|---|---|
db.Database.Migrate() at startup | Single-instance apps, dev, demos | Several instances racing; app needs DDL rights |
dotnet ef database update in a pipeline step | Most teams | Needs the SDK and the project on the agent |
--idempotent SQL script applied by a DBA | Regulated or locked-down environments | Slower loop, script must be reviewed |
| A one-off migration job or init container | Containerised deploys | Extra orchestration to write |
The failure worth knowing about is the first one. Three replicas starting at once all call Migrate(), all see the same pending migration, and two of them fail on a duplicate object — or, on a database without transactional DDL, leave the schema half-applied. If you must migrate from the application, do it from exactly one place: a leader instance, a startup job, or a separate entry point.
Expand and contract: changing a column with the lights on
The rule is that the database must be compatible with both the old and the new version of the code at every moment, because during a rolling deployment both are running.
- Expand. Add the new column as nullable. Deploy. Old code ignores it; nothing breaks.
- Write both. Deploy code that writes the old and the new column, and reads the old one.
- Backfill. Move existing data with a set-based, restartable statement.
- Switch reads. Deploy code that reads the new column. Now nothing depends on the old one.
- Contract. Make the new column required if it should be, then drop the old column in a separate, later migration.
Steps 1 and 5 are separate deployments on purpose. Dropping a column in the same release that stops reading it means any instance still running the previous build starts throwing on a missing column.
Keeping queries in step with the schema
A schema change is only half the job; the queries have to keep matching the indexes you now have.
// Offset paging: the server must count and discard 100,000 rows to give you 20.
var slow = await db.Orders.OrderBy(o => o.Id)
.Skip(100_000).Take(20).ToListAsync();
// Keyset paging: an index seek, and the cost does not grow with the page number.
var fast = await db.Orders
.Where(o => o.Id > lastSeenId)
.OrderBy(o => o.Id)
.Take(20)
.ToListAsync();
Two more rules save most query regressions. First, do not wrap a column in a function inside Where: o.Sku.ToUpper() == "BOLT-01" cannot use an index on Sku, because the server must compute UPPER for every row before comparing — fix the data or use a case-insensitive collation instead. Second, ask the question you actually mean: Any() translates to EXISTS and stops at the first match, while Count() > 0 counts every matching row first.
Composite indexes are order-sensitive in the same way. An index on (CustomerId, Sku) serves WHERE CustomerId = @c and WHERE CustomerId = @c AND Sku = @s, but not WHERE Sku = @s alone. When a migration adds a filter to a hot query, adding the matching index belongs in the same migration.
Real World Example: Splitting a Column on a Live System
Customers.Name has to become FirstName and LastName. In the real system this is three migrations across three deployments; the program below runs those same three steps inline against an in-memory database so you can watch the table at each stage, exactly as migrationBuilder.Sql(...) would execute them:
using System;
using Microsoft.Data.Sqlite;
class Program
{
static void Main()
{
using var conn = new SqliteConnection("Data Source=:memory:");
conn.Open();
Run(conn, @"
CREATE TABLE Customers (
Id INTEGER PRIMARY KEY,
Name TEXT NOT NULL
);
INSERT INTO Customers (Id, Name) VALUES
(1, 'Ada Lovelace'),
(2, 'Grace Hopper'),
(3, 'Prince');");
Show(conn, "v1", "SELECT Id, Name FROM Customers ORDER BY Id;");
// Migration 1 - EXPAND. Nullable columns, no data touched, old code unaffected.
Run(conn, @"
ALTER TABLE Customers ADD COLUMN FirstName TEXT NULL;
ALTER TABLE Customers ADD COLUMN LastName TEXT NULL;");
Show(conn, "expand",
"SELECT Id, Name, FirstName, LastName FROM Customers ORDER BY Id;");
// Migration 2 - BACKFILL. Set-based, and restartable: the WHERE clause means
// running it twice is harmless and a half-finished run can be resumed.
Run(conn, @"
UPDATE Customers
SET FirstName = CASE WHEN instr(Name, ' ') > 0
THEN substr(Name, 1, instr(Name, ' ') - 1)
ELSE Name END,
LastName = CASE WHEN instr(Name, ' ') > 0
THEN substr(Name, instr(Name, ' ') + 1)
ELSE '' END
WHERE FirstName IS NULL;");
Show(conn, "backfill", "SELECT Id, FirstName, LastName FROM Customers ORDER BY Id;");
// The guard that belongs in front of every destructive step.
long unmapped = Scalar(conn,
"SELECT COUNT(*) FROM Customers WHERE FirstName IS NULL;");
Console.WriteLine("unmapped: " + unmapped);
// Migration 3 - CONTRACT. A later deployment, once nothing reads Name.
if (unmapped == 0)
Run(conn, "ALTER TABLE Customers DROP COLUMN Name;");
Show(conn, "contract", "SELECT Id, FirstName, LastName FROM Customers ORDER BY Id;");
}
static void Run(SqliteConnection conn, string sql)
{
using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
static long Scalar(SqliteConnection conn, string sql)
{
using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
return (long)cmd.ExecuteScalar()!;
}
static void Show(SqliteConnection conn, string label, string sql)
{
using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
using var reader = cmd.ExecuteReader();
Console.WriteLine(label + ":");
while (reader.Read())
{
var parts = new string[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
string text = reader.IsDBNull(i) ? "NULL" : reader.GetValue(i).ToString()!;
parts[i] = text.Length == 0 ? "(empty)" : text;
}
Console.WriteLine(" " + string.Join(" | ", parts));
}
}
}
Output:
v1:
1 | Ada Lovelace
2 | Grace Hopper
3 | Prince
expand:
1 | Ada Lovelace | NULL | NULL
2 | Grace Hopper | NULL | NULL
3 | Prince | NULL | NULL
backfill:
1 | Ada | Lovelace
2 | Grace | Hopper
3 | Prince | (empty)
unmapped: 0
contract:
1 | Ada | Lovelace
2 | Grace | Hopper
3 | Prince | (empty)
The expand stage is the one that makes the whole thing safe, and it is the one people skip. Two new nullable columns are invisible to code that does not mention them, so the previous build keeps serving traffic against the same table without noticing. Had the columns been added as NOT NULL with no default, the migration itself would have failed on the existing rows; had Name been dropped in the same step, every instance of the old build would have started erroring the moment the migration landed.
The backfill is written to be run more than once. WHERE FirstName IS NULL means a second run is a no-op, and a run that dies halfway through — a timeout, a deploy, a restarted pod — can simply be started again and will pick up the rows it did not reach. On a table of ten million rows this statement would also be batched, updating a bounded number of rows per pass in a loop, so that it never holds a lock long enough to block the application. A single unbounded UPDATE over a large table is a genuine outage risk even though it looks like the simplest possible statement.
Prince is the row that justifies the guard. Real name data does not split cleanly: single names, three names, suffixes, names where the family name comes first. The CASE expression produces an empty LastName rather than a NULL, so the unmapped count is zero and the contract step is allowed to proceed — but on real data that count is how you discover the two hundred rows your split did not handle, before the original values are gone. Never drop the source column in the same migration that reads it; the entire point of a separate contract deployment is that you get a window in which the old data still exists.
One provider-specific detail is visible in the last step. ALTER TABLE ... DROP COLUMN is a recent addition to SQLite, and on older versions EF Core implements a column drop by creating a new table, copying the rows, dropping the original and renaming — which is why a SQLite migration that looks like one line can generate twenty. It is worth reading the generated SQL with dotnet ef migrations script for any destructive change, on any provider, before it touches data you cannot regenerate.
Common Mistakes
- Applying a generated migration without reading it. A property rename comes out as
DropColumnplusAddColumn, which silently deletes a column of data. Every migration is a code review item, and destructive operations are the reason. - Deleting a migration file by hand. The model snapshot still describes the state that file produced, so the next
migrations addgenerates a nonsensical diff. Usedotnet ef migrations remove, and only while the migration is still unapplied. - Merging
ShopContextModelSnapshot.csmanually. The result matches neither branch and every subsequent migration is wrong. Rebase,removeyour migration, take theirs, regenerate. - Calling
Migrate()from every instance at startup. Replicas race, some fail on objects that already exist, and a partially applied schema is possible on databases without transactional DDL. Migrate from exactly one place. - Using
EnsureCreatedand migrations in the same project.EnsureCreatedbuilds the schema without writing history rows, so the firstdatabase updatetries to create tables that already exist. Pick one, and for anything long-lived pick migrations. - Opening a
DbContextinside a migration. The migration is compiled against today's entities but will still be executed in two years against a database at an old version. UsemigrationBuilder.Sqlso the statement is fixed forever. - Dropping the old column in the same release that stops reading it. During a rolling deployment the previous build is still running and still selects that column. Contract in a later, separate deployment.
- Backfilling a large table in one unbounded
UPDATE. It holds locks, grows the log, and blocks the application for as long as it takes. Batch it, keep theWHEREclause that makes it restartable, and let it run in the background.
Best Practices
- Treat migrations as reviewed, immutable code once they are applied anywhere: fix a mistake with a new migration, never by editing one that has shipped.
- Give each migration a name that describes the change (
AddOrderShippedOn,SplitCustomerName) somigrations listreads like a changelog. - Run
dotnet ef migrations script --idempotentin CI and attach the output to the deployment, so the exact SQL is known and reviewable before it touches production. - Apply migrations from a single well-defined step — a pipeline task, an init job, or a leader instance — rather than from every replica at startup.
- Follow expand, write-both, backfill, switch-reads, contract for any change that removes or narrows a column, and give each phase its own deployment.
- Put data movement in
migrationBuilder.Sqlwith a restartableWHEREclause, batched when the table is large. - Add the index that a new query needs in the same migration as the query's release, and keep composite index order aligned with the predicate order.
- Keep a fast way to rebuild a development database from scratch —
dotnet ef database dropplusupdate— and run it regularly so the migration chain is proven, not assumed.
Practice Exercises
- Build the chain from scratch. Create a project with the
Customer/Ordermodel, add anInitialCreatemigration, apply it, then add aShippedOnproperty and generate a second migration. Read both files, rundotnet ef migrations script, and find the__EFMigrationsHistoryinserts in the output. - Catch a data-destroying rename. Rename a property in the model and generate the migration without applying it. Confirm it contains
DropColumnandAddColumn, replace them withRenameColumn, apply it, and verify the values survived. - Do the expand and contract properly. Split a
Addresscolumn intoStreetandCityacross three migrations, seeding a dozen rows first — including at least two that do not split cleanly. Make the backfill restartable, add a count check before the contract step, and confirm no row loses data. - Prove keyset paging wins. Insert two hundred thousand orders, then fetch page 5000 twice: once with
Skip/Takeand once with aWHERE Id > lastSeenIdkeyset query. Time both, then remove the supporting index and time them again to see which one degrades.