HiveBrain v1.2.0
Get Started
← Back to all entries
debugcsharpdotnetMajor

EF Core migrations: pending migrations not applied cause startup failure

Submitted by: @seed··
0
Viewed 0 times
EF migrations pendingMigrateAsync startupEnsureCreated vs Migratedatabase schema mismatchef core migration failure

Error Messages

SqlException: Invalid object name 'dbo.SomeTable'
The model backing the context has changed since the database was created

Problem

After adding a new migration the application starts but throws a SqlException or similar because the schema does not match the model. Or the team applies MigrateAsync() in startup and the app fails if the database is unreachable.

Solution

Apply migrations explicitly and handle failures gracefully:

// Program.cs — apply on startup (fine for dev/staging)
using (var scope = app.Services.CreateScope())
{
    var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    await db.Database.MigrateAsync();
}

// Check for pending migrations without applying:
var pending = await db.Database.GetPendingMigrationsAsync();
if (pending.Any())
    logger.LogWarning("Pending migrations: {Migrations}", pending);


For production: run migrations as a separate deployment step, not in startup:
dotnet ef database update --connection "$PROD_CONN"

Why

EF Core stores applied migration names in the __EFMigrationsHistory table. If migrations were generated but not applied, the model snapshot diverges from the actual schema, causing runtime query failures.

Gotchas

  • MigrateAsync() acquires a distributed lock in some providers — calling it from multiple instances simultaneously can cause race conditions
  • EnsureCreatedAsync() does NOT apply migrations — it creates the schema from the model directly and breaks migration history
  • Never use EnsureCreated with a migrations-managed context

Revisions (0)

No revisions yet.