Volume 3 · Chapter 5 — Entity Framework Core and Data Access Engineering

Migrations and Database Evolution

Goutham Mayaluri 9 min read .NETC#Migrations

5.1 Introduction

Database schemas evolve constantly as requirements change, and EF Core migrations provide a version- controlled way to track, review, and apply those changes. In enterprise systems this is high-stakes: applied carelessly, a schema change can lock tables, break running application versions, or corrupt data. The defining technique for safe, zero-downtime evolution is the expand-and-contract pattern, which lets old and new application versions run against the same database during a deployment.

5.2 How Migrations Work

A migration captures the difference between your current entity model and the last recorded model snapshot, generating anUpmethod (apply the change) and aDownmethod (revert it). A model snapshot records the current model state, and a history table in the database tracks which migrations have been applied - so EF Core knows what to run.

flowchart TB
  Model["Entity model change"] --> Gen["dotnet ef migrations add"]
  Gen --> Files["Migration (Up/Down) + updated snapshot"]
  Files --> Apply["dotnet ef database update / migration bundle"]
  Apply --> Hist["__EFMigrationsHistory records it"]
  Hist --> Schema["New schema version"]

// Create and apply a migration (CLI):
//   dotnet ef migrations add AddTransactionMetadata
//   dotnet ef database update
// For production, generate a SQL script or migration bundle to review and run in a controlled release:
//   dotnet ef migrations script --idempotent

5.3 Production Migration Discipline

Never blindly auto-apply migrations to production. Review the generated SQL, test it against production-like data, back up first, apply during controlled releases, and monitor execution time (a change that rewrites a huge table can lock it for a long time). Generating an idempotent SQL script or a migration bundle for the deploy pipeline is safer than runningdatabase updatelive.

5.4 Zero-Downtime with Expand and Contract

When old and new application versions run simultaneously during a rolling deploy, the schema must be compatible with both. The expand-and-contract pattern makes every change backward-compatible: firstexpand(add the new column/table, nullable, without removing anything), then deploy the app that uses it, then latercontract(remove the old structure once no running version needs it).

sequenceDiagram
  autonumber
  participant DB as Database
  participant AppOld as App v1
  participant AppNew as App v2
  Note over DB: Phase 1 - EXPAND
  DB->>DB: add new column (nullable, additive)
  Note over AppOld,AppNew: both versions work (old ignores new column)
  Note over DB: Phase 2 - MIGRATE + DEPLOY
  AppNew->>DB: write both old and new; backfill data
  Note over DB: Phase 3 - CONTRACT
  DB->>DB: drop old column once no version needs it

5.5 Seed Data, CI/CD, and Rollback

Seed data initializes reference/lookup values and system records. Migrations should run through the CI/CD pipeline (validate, then apply as part of a controlled release). Rollback is hard because reverting schema can lose data, so the safest strategy is backward-compatible changes plus roll-forward fixes, backed by tested backups - rather than relying on reverse migrations against live data.

Senior Interview Question

Why are production database migrations risky, and how do you apply them safely?

Production migrations are risky because, unlike application code, they act on live data and shared state that can’t simply be redeployed if wrong. A schema change can lock a large table for a long time while it rewrites it (blocking the running application), can break the currently-deployed application version if it’s not backward-compatible (during a rolling deploy, old and new code briefly run against the same schema), and can irreversibly transform or lose data. So a bad migration can cause downtime, errors, or data corruption that’s hard to undo. To apply them safely I follow a disciplined process. I review the generated SQL rather than trusting the migration blindly, because EF’s generated operations can hide expensive or locking changes. I test the migration against production-like data and volume to catch performance/locking problems and verify correctness before it ever touches production. I back up critical data first so I have a recovery path. I apply migrations through a controlled release process - typically generating an idempotent SQL script or a migration bundle that the deployment pipeline runs, rather than executingdatabase updatelive/ad hoc - so the change is reviewed, versioned, and repeatable. I monitor execution time and impact during the apply, and schedule large/locking changes for low-traffic windows or use online/low-lock techniques. Crucially, for systems that must stay available during rolling deploys, I make changes backward-compatible using expand-and-contract (add new structures without removing old ones, deploy, then remove the old later) so both application versions work throughout. And I plan rollback: prefer roll-forward fixes and backward-compatible changes over reverse migrations that could lose data, backed by tested backups. So the risk comes from acting on live, shared, hard-to-revert data and possibly locking tables or breaking running versions, and the mitigation is: review and test the SQL, back up, apply through a controlled pipeline, make changes backward-compatible (expand-and-contract) and monitor - treating schema changes with the same or greater rigor as code changes, because their blast radius is larger and harder to reverse.

Senior Interview Question

Explain the expand-and-contract pattern for zero-downtime schema changes.

Expand-and-contract (also called parallel-change) is the technique for evolving a database schema without downtime when you can’t take the application offline and when, during a rolling deployment, old and new code versions run simultaneously against the same database. The core requirement it satisfies is that every intermediate state of the schema must be compatible with both the old and new application versions. It works in three phases. Expand: make an additive, backward-compatible schema change that doesn’t break the old code - for example add a new column (nullable, with a default) or a new table, but don’t remove or rename anything the old version depends on. At this point the old application still works (it ignores the new column) and the new application can start using it. Migrate and deploy: deploy the new application version that writes to both the old and new structures (or the new one), and backfill existing data into the new structure so it’s populated; during the rollout, some instances are old and some new, and both function because the schema supports both. Contract: once every running version uses only the new structure and no version depends on the old one anymore, remove the old column/table in a later migration. So a rename becomes “add new column → write both and backfill → switch reads to new → stop writing old → drop old,” each step backward-compatible. The pattern avoids the downtime and breakage you’d get from doing a destructive change (drop/rename) in one shot while old code is still running, which would either break the old version or require taking the app down. It requires more steps and careful sequencing, and the application code temporarily handles both shapes, but that’s the price of zero-downtime evolution. This is essential for always-on enterprise systems - especially banking - where you can’t take the database offline, and it’s the standard answer for how to make schema changes safely during rolling deployments: never do a breaking change in place; expand additively, migrate, then contract once it’s safe.

Principal Engineer Question

A high-volume system needs to add transaction-metadata fields while millions of transactions are processed daily. How do you do it safely?

With an always-on, high-volume system I can’t take an outage or lock the huge transactions table, and old and new application versions will run together during the rolling deploy, so I use expand-and-contract with careful attention to locking and backfilling at scale. Expand phase: add the new metadata columns as nullable (or with a safe default) in a migration that is a fast metadata-only operation - adding a nullable column is typically quick and non-locking on modern databases, whereas adding a NOT NULL column with a computed default that rewrites every row would lock the table, so I deliberately keep the additive change cheap and avoid a full-table rewrite. The old application version continues working because it simply ignores the new columns. Deploy phase: roll out the new application version that populates the new metadata on new and updated transactions; because both versions run during the rollout, the schema (old columns present, new columns optional) supports both. Backfill phase: for existing historical rows that need the new metadata, I backfill in controlled batches - a background job that updates rows in small chunks with pauses, rather than one massive UPDATE that would lock the table and generate huge transaction-log load - so the backfill runs without impacting live traffic, and I monitor its progress and system load. Only once new writes populate the fields and the historical backfill is complete do I consider making the columns NOT NULL or adding related constraints/indexes, and I add any needed indexes carefully (online index builds if the platform supports them, off-peak if not) since indexing a hundreds-of-millions-row table is itself a heavy operation. If I later needed to remove or rename old fields, that’s the contract phase, done only after no running version depends on them. Throughout, I generate and review the migration SQL, test against production-scale data to verify the operations are non-locking and fast, apply via the controlled deployment pipeline (idempotent script/bundle), back up, and monitor execution time and locking during each step, with a roll-forward plan rather than risky reverse migrations. So the safe approach is: additive, non-locking schema change (nullable columns) via expand-and-contract so both app versions keep working, populate new data on writes, backfill history in throttled batches to avoid locking and log pressure, add constraints/ indexes carefully and off-peak, and drive it all through reviewed, tested, monitored controlled releases - which lets a busy system evolve its schema with zero downtime and no disruption to the millions of daily transactions.

5.6 Production Scenario

A banking platform must add transaction-metadata fields while millions of transactions flow daily. The team uses expand-and-contract: they add the new columns as nullable (a fast, non-locking change), deploy the new application version that populates them on writes, backfill historical rows in throttled batches to avoid locking and log pressure, and only later add constraints and indexes off-peak - evolving the schema with zero downtime and no disruption, all through reviewed, tested, pipeline-driven releases.

Chapter Revision Notes

  • Migrations diff the model against a snapshot, generating Up/Down; a history table tracks applied ones.
  • Review and test generated SQL; apply via controlled releases (scripts/bundles), not blind live updates.
  • Use expand-and-contract for zero-downtime: additive change → deploy → remove old once safe.
  • Backfill large tables in throttled batches to avoid locking and log pressure.
  • Prefer backward-compatible changes and roll-forward fixes over risky reverse migrations.