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.
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.
"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
DropColumnandAddColumn, 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 withmigrationBuilder.RenameColumn, which becomessp_rename, plus the reverse inDown, then apply any length change as a separateAlterColumn. 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 ofPhonetoMobileNumberwould 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 rundotnet ef migrations add Probeand read what EF Core thinks changed. If it's a real change someone forgot, I keep the migration. If the probe contains the sameUpdateDataevery time, the model is non-deterministic: almost alwaysHasDatawithDateTime.NoworGuid.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 withConfigureWarnings(w => w.Ignore(...)), which just hides schema drift."
| 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 |
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.
Checks that the candidate reviews migrations and understands how EF Core generates and validates them.
Green flags
RenameColumn and keeps Down symmetricRed flags
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.
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.
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.
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.
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.
RenameColumn + AlterColumn, apply it, and check the data survived.HasData with DateTime.UtcNow, run migrations add twice, and compare.dotnet ef migrations has-pending-model-changes in a CI job.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
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.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.sp_rename doesn't update them. Instead: search dependencies (sys.sql_expression_dependencies).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 |
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.__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.
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.
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.
Last updated 23 Nov 2026.