
Why Database.Migrate() at Startup Is Risky in Production
- كاتب موثّق
- EF Core 10
محتويات المقال
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
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.
What actually happens
The lock fixed the race, not the rollout
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."
Old code meets the new schema
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.
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
Failures happen at the worst moment
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
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();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>(); if (app.Environment.IsDevelopment()) await db.Database.MigrateAsync(); // local convenience only else if ((await db.Database.GetPendingMigrationsAsync()).Any()) // The deploy job should have run first: fail before serving traffic throw new InvalidOperationException("Database schema is behind");}app.Run();# 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 userdotnet 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 startup | ||
|---|---|---|
How to apply it in your project
Take migration out of production startup Keep MigrateAsyncbehindIsDevelopment()for local work and tests, and have production only checkGetPendingMigrationsAsyncand fail fast.Build the artifact in CI Add the pending-model-changes check, then produce a bundle, or an idempotent script when someone must approve the SQL. Run it once, with its own identity Apply 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. Make each migration backward compatible Add 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.
التعليقات (0)