skip to content

In EF Core 10, why might MigrateAsync throw that the model for PayrollDbContext has pending changes, and how do you find and fix the cause?

level: seniorimportance: should knowfreq 48%

answer

  1. PendingModelChangesWarning defaults to Throw
  2. current model vs the migrations' snapshot
  3. non-deterministic HasData values
  4. has-pending-model-changes in CI
  5. ConfigureWarnings only for false positives

basics

~20 s

Since EF Core 9, migrating to the latest migration first compares the current model with the snapshot and throws if they differ, usually a forgotten migration. Add the migration, and gate CI with dotnet ef migrations has-pending-model-changes.

solid answer

~50 s

Before migrating to the latest migration, `Migrate`, `MigrateAsync`, `dotnet ef database update` and bundles compare the runtime model with the snapshot from the last migration. A difference logs `RelationalEventId.PendingModelChangesWarning`, which relational providers treat as an error since EF Core 9, so startup fails with *The model for context 'PayrollDbContext' has pending changes. Add a new migration before updating the database.* Usual causes: a model change without a migration, `HasData` values such as `DateTime.UtcNow` that change every build (reported as a model that changes each time it is built), runtime configuration that differs from design time, or migrations scaffolded for another provider. Fix the cause and add the migration, then stop it recurring with `dotnet ef migrations has-pending-model-changes` in CI or a test on `context.Database.HasPendingModelChanges()`. Suppress the warning with `ConfigureWarnings` only for a confirmed false positive.

code

csharp · 11 lines
csharp
[Fact]
public void Model_has_no_changes_missing_from_a_migration()
{
    var options = new DbContextOptionsBuilder<PayrollDbContext>()
        .UseNpgsql("Host=localhost;Database=payroll_design")
        .Options;

    using var db = new PayrollDbContext(options);

    Assert.False(db.Database.HasPendingModelChanges());
}

go deeper

for a junior

Recall that forgetting to add a migration after changing the model makes migrating fail, and that adding the migration fixes it.

for a middle

Explain that the check compares the runtime model with the snapshot, why non-deterministic HasData triggers it, and how it differs from GetPendingMigrationsAsync.

for a senior

Diagnose design-time versus runtime configuration drift, gate CI with has-pending-model-changes or a HasPendingModelChanges test, and refuse suppression as a deploy workaround.

for a principal

Make model and migration consistency a release gate, and decide how teams handle model-shaping options that live outside OnModelCreating.

## What the check compares Two models are involved whenever migrations are applied: - the **runtime model**, built from your entity classes and `OnModelCreating` as the app is configured right now; - the **snapshot model**, the `ModelSnapshot` class that `dotnet ef migrations add` last wrote, describing what the migrations produce. When `Migrate`, `MigrateAsync`, `dotnet ef database update` or a migration bundle applies migrations **to the latest one** (no explicit target), EF Core first asks whether the two differ. If they do, it logs `RelationalEventId.PendingModelChangesWarning`. Relational providers configure that event to **throw** by default, so the call fails before any migration runs: *The model for context 'PayrollDbContext' has pending changes. Add a new migration before updating the database.* Two edge cases change the outcome: with a named target (`Migrate("AddPayslipTaxCode")`) the check is skipped, and with no migrations at all EF Core logs that none were found instead. ## Causes, from most to least common 1. **A model change without a migration.** Someone added `Payslip.TaxCode` and committed no migration. 2. **A model that changes on every build.** `HasData` objects with `DateTime.UtcNow`, `new DateTime()` or `Guid.NewGuid()` produce a different model each time. EF Core recognises this case and reports instead that the model *changes each time it is built*, pointing at `HasData`. 3. **Design time and runtime disagree.** The migration was scaffolded with one configuration and the app runs with another: options that shape the model are set only in the web app (ASP.NET Core Identity's store options are the documented example), model configuration depends on the environment, or a design-time factory omits a provider option. 4. **Migrations scaffolded for another provider** than the one applying them, which is unsupported; keep one migration set per provider. ## Finding the cause - Run `dotnet ef migrations add Probe` and read what it scaffolds: the operations name the difference. Then `dotnet ef migrations remove`. - If every new probe contains the same `UpdateData`, look for non-deterministic `HasData` values. - If the probe is empty locally but the app still throws, the runtime configuration differs from design time: compare the environment, options and provider. ## Fixing and preventing it | Cause | Fix | |---|---| | Forgotten migration | add it, review it, deploy it | | Non-deterministic `HasData` | replace the dynamic value with a literal, then re-create the migration | | Design time differs from runtime | make the startup project or the `IDesignTimeDbContextFactory<TContext>` configure the model exactly as the app does | | Wrong provider's migrations | separate migration sets per provider | Prevention belongs in CI: - `dotnet ef migrations has-pending-model-changes` builds the project and fails with *Changes have been made to the model since the last migration. Add a new migration.*, or prints that there are none; - a unit test asserting `context.Database.HasPendingModelChanges()` is `false` gives the same guard inside the test suite; - neither needs a database connection; both compare the model with the snapshot. ## When suppressing is acceptable `options.ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning))` turns the check off. The EF Core docs reserve it for real false positives, such as migrations generated or chosen dynamically by replaced EF services. Suppressing it to make a deploy pass ships a database that does not match the model. ## Not the same as pending migrations `GetPendingMigrationsAsync()` lists migrations in the assembly that the database has not recorded in `__EFMigrationsHistory`. It says nothing about model changes missing from a migration. A startup health check built on it alone misses exactly the problem this error reports. ## Upgrading from EF Core 8 Before EF Core 9, `Migrate` applied the existing migrations and silently ignored a model change nobody had captured; the app then failed later, on the first query touching the missing column. A service upgraded from 8 to 10 can therefore start failing at deploy time on a defect it has carried for months. The upgrade checklist: 1. run `dotnet ef migrations has-pending-model-changes` on the upgraded branch before deploying; 2. if it reports changes, scaffold a migration and read it: it is either the forgotten change or a sign of non-deterministic model building; 3. only after that, add the CI gate so the next forgotten migration fails the build instead of the deploy.

  • Why does Migrate("AddPayslipTaxCode") succeed when Migrate() throws for pending changes?
    EF Core runs the pending-model-changes check only when migrating to the latest migration. A named target is an explicit request for an intermediate state, which the current model is not expected to match, so the check is skipped. That is not a fix; the latest state still lacks the change.
  • The error appears on every deploy even right after adding a migration; what do you look for?
    A model that differs on every build. `HasData` values computed at runtime, such as `DateTime.UtcNow` or `Guid.NewGuid()`, make each model unique; EF Core then reports that the model changes each time it is built. Replace them with literals, or move that data to `UseSeeding`, and re-create the migration.

  • GetPendingMigrationsAsync reports model changes that have no migration yet.
  • The pending-model-changes error means the database schema differs from the model.
  • Suppressing PendingModelChangesWarning is the standard fix after upgrading to EF Core 9.
  • HasData with DateTime.UtcNow is fine because the value is only used once.
  • has-pending-model-changes needs a live database connection to compare schemas.

Assumes EF Core 10; since EF Core 9 relational providers set PendingModelChangesWarning to throw, while EF Core 8 applied the existing migrations and ignored the uncaptured change.