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

📚 Interview question

You renamed a property, but the generated EF Core migration drops the column and adds a new one. On another branch, Database.Migrate() now fails with a 'pending model changes' error on EF Core 9 or later. How do you review and fix both problems?

Covers debugging EF Core migrations: why the differ scaffolds drop and add instead of a rename, the data-loss warning, editing a migration to RenameColumn, and the EF Core 9+ PendingModelChangesWarning including non-deterministic seed data.

Mid-Level Debugging Intermediate data-loss debugging ef-core migrations pending-model-changes schema-changes

🎯 Key points

  • The differ matches columns by name, type and facets; a pure rename can be detected, but a rename combined with other changes becomes DropColumn + AddColumn
  • Watch for 'An operation was scaffolded that may result in the loss of data'
  • Fix by editing the unapplied migration: RenameColumn (and Down) or a HasColumnName mapping
  • EF Core 9+ Migrate() throws when the model differs from the last snapshot (PendingModelChangesWarning as error)
  • Common causes: forgotten migration, non-deterministic HasData (DateTime.Now, Guid.NewGuid()), model differs per environment
  • dotnet ef migrations has-pending-model-changes in CI; a probe migration shows what EF Core thinks changed
  • Run the script against a staging copy of production and check row counts before release
  • Suppress the warning only for a documented edge case, never as the fix

⏱ 30-second answer

Problem 1: the migrations differ only compares the old snapshot with the new model; it doesn't know you meant a rename. When it can't match the column (often because the rename came with other changes), it scaffolds DropColumn + AddColumn and prints "An operation was scaffolded that may result in the loss of data". Fix the unapplied migration by hand: replace both with RenameColumn (and the reverse in Down), or keep the old column name with HasColumnName.

Problem 2: since EF Core 9, Migrate() throws if the model differs from the latest snapshot (PendingModelChangesWarning is an error). Either a migration is missing, or the model isn't deterministic, usually HasData with DateTime.Now or Guid.NewGuid(). Add a migration to see what EF Core thinks changed, then fix the cause.

The trade-off: generated migrations save time, but they are a draft you must review.

🗣 Full answer (senior)

How I would answer this in an interview

"Both problems come from the same fact: migrations are generated by comparing two models, the snapshot from the last migration and the model the code builds now. The differ has no idea what I intended.

For the rename, EF Core can sometimes match a renamed property to its old column, but when the rename comes with another change, like a new max length, a type change or moving it into a complex type, it sees one column disappear and another appear. So it scaffolds DropColumn and AddColumn, and the CLI prints 'An operation was scaffolded that may result in the loss of data. Please review the migration for accuracy.' In production that's every value in the column gone. Because the migration hasn't been applied anywhere yet, I edit it: replace the pair with migrationBuilder.RenameColumn, which becomes sp_rename, plus the reverse in Down, then apply any length change as a separate AlterColumn. If I don't actually need the database column renamed, HasColumnName("OldName") is even simpler. For example, at [company] we caught exactly this in review: a rename of Phone to MobileNumber would have wiped [1.2 million] numbers.

The second error is new behaviour in EF Core 9. Migrate() now checks that the model matches the last migration's snapshot and throws if it doesn't, instead of silently applying old migrations. The first thing I do is run dotnet ef migrations add Probe and read what EF Core thinks changed. If it's a real change someone forgot, I keep the migration. If the probe contains the same UpdateData every time, the model is non-deterministic: almost always HasData with DateTime.Now or Guid.NewGuid(), which changes on every build. I fix the seed to use constants and remove the probe. The mistake I see is suppressing the warning with ConfigureWarnings(w => w.Ignore(...)), which just hides schema drift."


Diagnosis table

Symptom Cause Fix
Drop + add for a rename Differ can't match columns Edit migration to RenameColumn; or HasColumnName
"may result in the loss of data" Drop, narrowing type, NOT NULL without default Review and rewrite the operation
Pending model changes (EF 9+) Missing migration Add and review a migration
Pending changes every time Non-deterministic HasData Constant seed values
Pending changes only in one environment Model built from config (e.g. schema name per env) Make the model environment-independent

Production example

After adding dotnet ef migrations has-pending-model-changes and a review rule for the data-loss warning, [two] destructive migrations were caught in pull requests over [six months], and no release failed on the EF Core 9 pending-changes check.

🔍 What the interviewer is checking

Checks that the candidate reviews migrations and understands how EF Core generates and validates them.

Green flags

  • Explains that the differ compares models, not intent
  • Rewrites to RenameColumn and keeps Down symmetric
  • Knows the EF Core 9 pending-changes check and non-deterministic seeds
  • Adds a CI gate

Red flags

  • Applies migrations unread
  • Suppresses the warning as the fix

📚 Learn in depth

1. How the differ matches columns

snapshot model                current model
Customer.Phone  nvarchar(20)   Customer.MobileNumber nvarchar(32)
         \                         /
          └── no match by name, different facets ──┘
                    ↓
   DropColumn(Phone) + AddColumn(MobileNumber)

The differ matches tables and columns by name and facets. A pure property rename with nothing else changed can be recognised; anything ambiguous is treated as remove + add.

2. What RenameColumn produces

EXEC sp_rename N'[Customers].[Phone]', N'MobileNumber', 'COLUMN';

sp_rename is a metadata change: fast, no data movement. Dependent views, stored procedures or computed columns are not updated, so search for them.

3. The EF Core 9 check

On Migrate()/MigrateAsync() EF Core compares the runtime model with the latest migration's snapshot. Differences raise PendingModelChangesWarning, configured as an error by default. Design-time builds use the same model, so dotnet ef migrations has-pending-model-changes reproduces it in CI.

4. Non-deterministic models

b.Entity<Plan>().HasData(new Plan { Id = 1, CreatedAt = DateTime.UtcNow }); // changes every build

The snapshot captures one value; the next build produces another, so the model always differs. Use fixed literals. Since EF Core 9, UseSeeding/UseAsyncSeeding are a better place for data that needs run-time values.

5. Editing migrations safely

You may edit a migration until it has been applied to any shared database. Keep Up and Down symmetric, and don't touch the .Designer.cs or snapshot by hand.

Try it yourself

  1. Rename a property and change its length in one commit; read the scaffolded migration and the CLI warning.
  2. Rewrite it with RenameColumn + AlterColumn, apply it, and check the data survived.
  3. Add HasData with DateTime.UtcNow, run migrations add twice, and compare.
  4. Run dotnet ef migrations has-pending-model-changes in a CI job.

💻 Code

The scaffolded migration, and the reviewed version that keeps the data.

// Scaffolded (destructive): DO NOT APPLY
protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.DropColumn(name: "Phone", table: "Customers");
    migrationBuilder.AddColumn<string>(
        name: "MobileNumber", table: "Customers",
        type: "nvarchar(32)", maxLength: 32, nullable: false, defaultValue: "");
}
namespace Shop.Infrastructure.Migrations;

using Microsoft.EntityFrameworkCore.Migrations;

public partial class RenamePhoneToMobileNumber : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.RenameColumn(name: "Phone", table: "Customers", newName: "MobileNumber");
        migrationBuilder.AlterColumn<string>(
            name: "MobileNumber", table: "Customers",
            type: "nvarchar(32)", maxLength: 32, nullable: false,
            oldClrType: typeof(string), oldType: "nvarchar(20)", oldMaxLength: 20);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AlterColumn<string>(
            name: "MobileNumber", table: "Customers",
            type: "nvarchar(20)", maxLength: 20, nullable: false,
            oldClrType: typeof(string), oldType: "nvarchar(32)", oldMaxLength: 32);
        migrationBuilder.RenameColumn(name: "MobileNumber", table: "Customers", newName: "Phone");
    }
}

The non-deterministic seed and its fix:

// Before: a new value on every build → pending model changes forever
b.Entity<Plan>().HasData(new Plan { Id = 1, Name = "Basic", CreatedAt = DateTime.UtcNow });

// After: constants only
b.Entity<Plan>().HasData(new Plan { Id = 1, Name = "Basic", CreatedAt = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc) });
dotnet ef migrations add Probe         # what does EF Core think changed?
dotnet ef migrations remove            # if it was only the seed bug
dotnet ef migrations has-pending-model-changes

⚠ Common mistakes

  • Mistake: Applying a migration without reading it. Why it is wrong: drop + add silently deletes data. Instead: review every migration; treat the data-loss warning as a blocker.
  • Mistake: Editing a migration already applied to a shared environment. Why it is wrong: databases diverge. Instead: a new corrective migration.
  • Mistake: Suppressing PendingModelChangesWarning globally as the default fix. Why it is wrong: it hides real schema drift. Instead: find the cause. Suppress (ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning))) only for a known, documented case, such as a model that legitimately varies by provider, with a comment and a ticket.
  • Mistake: Using DateTime.Now or Guid.NewGuid() in HasData. Why it is wrong: the model changes every build. Instead: constant literals in HasData; for data that needs run-time values, use the EF Core 9 UseSeeding/UseAsyncSeeding options on DbContextOptionsBuilder, which run during Migrate()/EnsureCreated() and aren't part of the model.
  • Mistake: Combining a rename and a type change in one scaffold without checking. Why it is wrong: most likely to produce drop + add. Instead: split or hand-edit the operations.
  • Mistake: Forgetting views and procedures that reference a renamed column. Why it is wrong: sp_rename doesn't update them. Instead: search dependencies (sys.sql_expression_dependencies).

🏛 Senior insight: trade-offs

A generated migration is a draft. The process fix is more valuable than the code fix: a CI gate (has-pending-model-changes), a pull-request rule that any migration with DropColumn, DropTable or narrowing AlterColumn needs a second reviewer, and idempotent scripts tested against a production-sized copy.

For data integrity, the staging step is concrete: restore last night's backup (or create an Azure SQL database copy) in a non-production subscription, run the exact idempotent script the pipeline will run, and compare before/after row counts and null counts on touched columns, plus how long it held locks. Keep the migration backwards-compatible with the running app version so a bad release is rolled back by redeploying, and know the point-in-time restore window before you start. Large data changes (backfills, type conversions) go in separate, batched steps rather than inside the schema migration.

Option When it fits Cost When not to
Edit to RenameColumn Unapplied migration, real rename needed Manual edit Already applied
HasColumnName("Old") Only the C# name matters Code and column names differ Clean naming is required
Expand/contract (add, copy, drop later) Zero-downtime with old app versions running Several releases Small internal apps
Suppress the warning Known, documented edge cases Hides drift As a default

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the snapshot. Why: Checks the base migrations workflow.
    How to 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.

  2. When: Candidate mentions RenameColumn in production. Why: Checks expand/contract thinking.
    How to answer

    Never use RenameColumn while old and new app versions overlap: the old version would query a column that no longer exists. Use expand and contract over several releases. 1. Expand: add the new column (nullable). 2. Dual write: release an app version that writes both columns in the same SaveChanges (same transaction), or add a trigger that copies writes made by the old version, and still reads the old column. 3. Backfill existing rows in small batches (UPDATE TOP (5000) ... WHERE New IS NULL) to avoid long locks and log growth, then verify with a count of mismatches. 4. Switch reads to the new column; keep writing both so a rollback to the previous version still works. 5. Contract: once no running version uses the old column, stop writing it and drop it in a later migration. Each step is backward compatible with the version before it.

🛠 Real-world problems: how you handle them

A rename migration would have wiped 1.2 million phone numbers
Situation
A customer service at [company] renamed `Phone` to `MobileNumber` and widened it to 32 characters in one change; the migration was in a pull request headed for the [Friday] release.
Signals
The `dotnet ef migrations add` output included 'An operation was scaffolded that may result in the loss of data'; the diff showed `DropColumn` and `AddColumn` with `defaultValue: ""`.
Investigation
Read the migration and the idempotent script; ran it against a restored copy of production on Azure SQL and confirmed every `MobileNumber` was empty afterwards. Checked `sys.sql_expression_dependencies` for views using `Phone`.
Resolution
Rewrote the migration as `RenameColumn` + `AlterColumn` with a symmetric `Down`; updated one reporting view in the same migration with `migrationBuilder.Sql`. Re-ran against the copy: data intact, migration took under a second.
Prevention
CI fails on `has-pending-model-changes`; a pull-request check flags migrations containing `DropColumn`/`DropTable` for a second reviewer; migration scripts are run against a production copy before release.

How to tell it (STAR)

**S:** At [company] a pull request renamed our customers' phone column and widened it in one go. **T:** I was reviewing it before the [Friday] release. **A:** The scaffold had produced a drop and an add, so I ran the script against a restored production copy and confirmed it emptied all [1.2 million] numbers. I rewrote it as `RenameColumn` plus `AlterColumn`, fixed a dependent view in the same migration and re-tested. Then I added a CI check that flags destructive operations for a second reviewer. **R:** The release went out with no data loss, and the check has since caught [two] more destructive migrations.

More in EF Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me