📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do EF Core migrations work? Explain how you add, script and apply a migration, what the model snapshot is for, what a migration file contains, and how a team handles migration merge conflicts.

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.

Junior Theory Intermediate dotnet-ef ef-core migrations model-snapshot schema-changes source-control

🎯 Key points

  • dotnet ef migrations add compares the model with the ModelSnapshot and writes Up/Down
  • Each migration = migration class + Designer file; snapshot = current model state
  • __EFMigrationsHistory records applied migration ids
  • dotnet ef migrations script --idempotent (or a bundle) for reviewed deployment in CI/CD
  • Review generated SQL for data loss: renames shown as drop + add, narrowing types, new NOT NULL columns
  • Merge conflicts show up in the snapshot; fix by removing your migration, merging, re-adding
  • Never edit an applied migration; add a new one
  • Since EF Core 9, Migrate() throws on pending model changes and takes a database-wide migration lock

⏱ 30-second answer

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.
  • The database records applied migrations in __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.

🗣 Full answer (senior)

How I would answer this in an interview

"Migrations are how EF Core versions the database schema alongside the code. When I change the model, say I add a Status column, I run dotnet 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 an Up method that adds the column and a Down method 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 with dotnet ef migrations script --idempotent, which wraps each migration in a check against the __EFMigrationsHistory table, 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."


The commands

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+)

What is in each file

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can use migrations safely in a team and knows how they reach production.

Green flags

  • Explains the snapshot and the history table
  • Knows the remove/merge/re-add conflict fix
  • Prefers scripts or bundles over start-up migration
  • Treats applied migrations as immutable

Red flags

  • Edits applied migrations
  • Has never looked at generated migration code

📚 Learn in depth

1. How a migration is generated

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.

2. How a migration is applied

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.

3. Idempotent scripts

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.

4. Team workflow

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.

5. Where the design-time context comes from

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.

Try it yourself

  1. Add an entity, run migrations add, and read the three files.
  2. Generate an idempotent script and run it twice against a local database.
  3. Create a conflict on two branches and resolve it with remove and re-add.
  4. Add dotnet ef migrations has-pending-model-changes to a CI workflow and make it fail.

💻 Code

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

⚠ Common mistakes

  • Mistake: Editing a migration that was already applied to a shared database. Why it is wrong: environments that already ran it never see the change. Instead: add a new migration.
  • Mistake: Deleting migration files by hand. Why it is wrong: the snapshot no longer matches. Instead: dotnet ef migrations remove.
  • Mistake: Resolving a snapshot merge conflict by hand-merging text. Why it is wrong: easy to produce a snapshot that differs from the real model. Instead: remove, merge, re-add.
  • Mistake: Calling 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.
  • Mistake: Not committing the snapshot. Why it is wrong: the next migration contains the whole model. Instead: commit all three files together.
  • Mistake: Never reading generated migrations. Why it is wrong: renames become drop + add and lose data. Instead: review every migration in the pull request.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions scripts or bundles. Why: Checks how migrations reach production through the pipeline.
    How to answer

    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.

  2. When: Candidate mentions applying migrations in CI/CD. Why: Checks knowledge of deployment options.
    How to answer

    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.

↩ Usually asked after

More in EF Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me