الانتقال إلى المحتوى
.NETEF Core· 7 دقائق للقراءة

Why Database.Migrate() at Startup Is Risky in Production

Since EF Core 9 a lock keeps replicas from migrating at the same time. Permissions, rolling deploys, rollbacks and unreviewed SQL are still your problem.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • EF Core 10
محتويات المقال

A release renames Customers.Email to ContactEmail, and the app applies its migrations in Program.cs. The rolling deploy starts the first new pod, which migrates the database and goes healthy. The four old pods are still serving traffic, and from that moment every customer query they run fails with SqlException: Invalid column name 'Email'. Someone hits rollback. The old image comes back, the renamed column doesn't, and the errors continue until a person writes and runs a reverse migration by hand.

The common misconception

The belief: calling Database.Migrate() when the app starts is the right way to apply EF Core migrations in production. The schema always matches the code that's running, the pipeline needs no extra step, and a fresh environment sets itself up.

There's a lot of truth in it, which is why it spreads. It's the snippet in countless templates, and Microsoft's own docs show it. The biggest classic objection, two replicas migrating at the same time, has been handled since EF Core 9, and the docs now say runtime migration can be acceptable for apps that prefer simple deployment and can tolerate its trade-offs. For a hobby project, an internal tool or an integration test, it's genuinely fine. Production web apps are where the remaining trade-offs bite.

What actually happens

The lock fixed the race, not the rollout

Starting with EF Core 9, Migrate and MigrateAsync take a database-wide lock before applying anything. In a test with EF Core 10 on SQL Server LocalDB, two processes started together on a database one migration behind. Both logged "Acquiring an exclusive lock for migration application". One applied the migration; the other waited about 5 seconds for it to finish, then logged "No migrations were applied. The database is already up to date."

That's real protection, and it also shows the cost: every new instance is stuck at startup for as long as the slowest migration runs, before it ever listens for requests. A migration that rebuilds a large index holds the whole rollout, and a platform that restarts slow-starting containers can kill the instance that's doing the migrating. On SQLite the lock is a table, and the docs warn it can be left behind if the process dies.

Old code meets the new schema

A rolling deploy runs old and new versions side by side by design. With startup migration, the schema changes the moment the first new instance starts, while every old instance still expects the old one. In the test, a context still mapped to Email failed with Invalid column name 'Email' as soon as the rename was applied. Rolling the app back doesn't roll the schema back, so the old version keeps failing.

The way out is to make every migration compatible with the code that's already running, a technique known as . Add ContactEmail next to Email and copy the data in one release, switch the code to the new column in the next, and drop Email only when nothing reads it. Microsoft's guidance for replacing columns follows the same order: populate the new column before dropping the old one.

The app holds the keys to the schema

Applying a migration means creating, altering and dropping tables. If the app migrates itself, the identity it uses for every request needs those permissions too. The docs recommend a separate deployment identity with schema rights, and an app identity limited to reading and writing data. Any bug, injection or compromised dependency in the running app then can't drop a table.

Failures happen at the worst moment

At startup, a failure doesn't stop a deploy; it stops your app. Since EF Core 9, Migrate throws when the model has changes that no migration captures. In the test, one forgotten migration turned into an InvalidOperationException about PendingModelChangesWarning before the app served a single request, and every replica would have crashed the same way. And the SQL runs without anyone having read it, though the docs warn that a generated migration can drop a column when you meant to rename it.

The fix: migrate once, before the rollout

C# Program.cs
using Microsoft.EntityFrameworkCore;var builder = WebApplication.CreateBuilder(args);builder.Services.AddDbContext<ShopDb>();var app = builder.Build();await using (var scope = app.Services.CreateAsyncScope()){    var db = scope.ServiceProvider.GetRequiredService<ShopDb>();    // Every replica, on every start, with the app's own credentials    await db.Database.MigrateAsync();}app.Run();

The right version only checks. Applying is the pipeline's job, with a : a single-file executable that runs without the .NET SDK, the EF tools or your source code, and uses the same migration lock.

Bash deploy.sh
# CI: build the bundle from the same commit as the app imagedotnet ef migrations has-pending-model-changesdotnet ef migrations bundle --self-contained --target-runtime linux-x64 \  --output artifacts/efbundle# Deploy: run it once, as a job, with the schema-owner connectionASPNETCORE_ENVIRONMENT=Production \  ./artifacts/efbundle --connection "$MIGRATIONS_CONNECTION"# Then roll out the app, which connects as a read/write-only user

If a DBA must review the SQL, generate dotnet ef migrations script --idempotent instead. An idempotent script checks the history table and applies only what's missing, though SQLite doesn't support generating one.

Migrate() at startupBundle or script in the pipeline
Two instances at onceSerialized by a lock since EF Core 9Runs once per deploy
The app's database rightsMust be able to change the schemaRead and write data only
A failing migrationEvery replica fails to startThe deploy stops before the rollout
Reviewing the SQLNot possiblePossible with a script
Old code on the new schemaFrom the first new instance onAt a step you plan for

How to apply it in your project

  1. Take migration out of production startupKeep MigrateAsync behind IsDevelopment() for local work and tests, and have production only check GetPendingMigrationsAsync and fail fast.
  2. Build the artifact in CIAdd the pending-model-changes check, then produce a bundle, or an idempotent script when someone must approve the SQL.
  3. Run it once, with its own identityApply the bundle as a one-shot job before the rollout, with a connection that can change the schema. Give the app a user that can only read and write data.
  4. Make each migration backward compatibleAdd columns before using them and drop them a release after nothing reads them, so a rollback of the app never meets a schema it can't use.

Key takeaways

  • Migrate() at startup runs on every replica, with the app's own permissions, in the middle of a rollout.
  • EF Core 9 and later serialize concurrent migrations with a lock, but every new instance waits for the migration before it serves traffic.
  • Rolling deploys run old code on the new schema, and rolling back the app doesn't roll back the schema.
  • Apply migrations once per deploy with a bundle or a reviewed script, using a separate schema-owning identity.
  • Write migrations in expand-and-contract steps so the previous release keeps working.

📚 المصادر

  1. Applying Migrations — EF Core, Microsoft Learn
  2. Migrations Overview — EF Core, Microsoft Learn
  3. Managing Migrations — EF Core, Microsoft Learn
  4. Parallel Change — Danilo Sato, martinfowler.com

التعليقات (0)