Recovering from a partly applied EF Core migration on Azure SQL: assessing state, forward fix vs Down migration vs point-in-time restore, idempotent scripts, transactional DDL and prevention.
First find out what state the database is actually in: read __EFMigrationsHistory, compare the schema with the expected script, and check the error. On SQL Server each migration normally runs in a transaction, so a failure usually rolls that migration back cleanly; the danger is statements EF Core runs outside a transaction and earlier migrations in the same batch that already committed.
Then restore service: if the schema is still compatible with the previous app version, redeploy it. Fix the problem with a reviewed forward fix, not by running untested Down() methods. Point-in-time restore is the last resort, for real data damage, because it loses every write since the restore point.
The trade-off: a forward fix keeps all data but takes thinking time; a restore is fast to start but expensive in lost writes.
"My first rule is: don't make it worse by guessing. Before touching anything I establish three facts: which migrations are recorded in
__EFMigrationsHistory, what the schema actually looks like, and what the error was. On SQL Server, EF Core wraps each migration in a transaction, so if the failing migration was a normal one it has rolled back and the only applied migrations are the earlier ones in the batch. The exceptions are statements that can't run in a transaction, or SQL marked withsuppressTransaction: true, and those can leave you half-done.Then I restore service, which is a separate problem from fixing the schema. If the new code is failing because its migration didn't apply, I redeploy the previous release, which works because our migrations are backward compatible. For example, at [company] a migration that created a unique index failed on [duplicate rows nobody knew existed]. The transaction rolled back, the new slot never swapped in, and the old version kept serving. We cleaned the duplicates with a reviewed script, re-ran the idempotent migration script, and shipped [two hours] later with no data loss.
The mistake I see is reaching for
dotnet ef database update <previous>to run theDownmethods. Down migrations are almost never tested, and a Down that drops a column drops the data written to it. I treat a forward fix as the default, Down only when it is trivial and reviewed, and point-in-time restore only when data itself has been damaged, because a restore loses every legitimate write since that moment. A rollback plan you haven't rehearsed is a hope, not a plan."
| Situation | Action |
|---|---|
| Migration failed, its transaction rolled back, old app still compatible | Keep or redeploy the old app; fix the migration; re-run the idempotent script |
| Partially applied (non-transactional step) | Write a script that completes or reverses the applied steps; record it in history only when the schema matches |
| Migration succeeded but new code is broken | Redeploy old code (schema is backward compatible); forward-fix the code |
Migration destroyed or corrupted data (bad UPDATE, wrong DROP) |
Point-in-time restore to a new database; copy back the lost data or switch over |
| No backward compatibility and app is down | Emergency forward fix or tested Down, under change control |
| Forward fix | Down migration | Point-in-time restore | |
|---|---|---|---|
| Data written since | Kept | Often lost (dropped columns) | Lost unless merged back |
| Tested? | Reviewed now | Usually never | Platform feature, but your runbook may not be |
| Speed | Minutes to hours | Fast if it works | Minutes to hours for large databases, plus switch-over |
| Best for | Most failures | Trivial, additive migrations | Data damage |
On a [payments API on Azure SQL Business Critical], a migration's CREATE UNIQUE INDEX failed on [1,200] duplicate rows. Because the migration was transactional and backward compatible, the error budget impact was [zero failed requests]. The fix took [two hours], including a reviewed de-duplication script and an idempotent re-run. A point-in-time restore would have discarded [about 40 minutes] of payments.
Checks calm incident handling: establishing facts first, separating service restoration from schema repair, and knowing the real cost of each recovery option.
Green flags
__EFMigrationsHistory and the schema before actingRed flags
dotnet ef database update (or the bundle / idempotent script)
├─ Migration A BEGIN TRAN ... INSERT __EFMigrationsHistory ... COMMIT ✔ applied
├─ Migration B BEGIN TRAN ... CREATE UNIQUE INDEX ✖ error → ROLLBACK ✘ not applied
└─ Migration C never started
On SQL Server, DDL is transactional, so CREATE TABLE, ALTER TABLE and CREATE INDEX roll back with the transaction. EF Core writes the history row in the same transaction, so history and schema agree. Each migration commits separately, so earlier migrations in the batch stay applied.
Partial state happens when:
migrationBuilder.Sql(..., suppressTransaction: true) (needed for some operations such as certain full-text or database-level statements),SELECT MigrationId, ProductVersion FROM __EFMigrationsHistory ORDER BY MigrationId;
-- Does the schema match what the migration should have produced?
SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('dbo.Orders');
SELECT name, is_unique FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.Orders');
Compare against dotnet ef migrations script A B for the failing migration. Every statement is either present or absent.
dotnet ef migrations script --idempotent wraps every migration in a check:
IF NOT EXISTS (SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20261101_AddUniqueEmail')
BEGIN
CREATE UNIQUE INDEX ...
END;
So once the cause is fixed you can run the same script again and it applies only what is missing. Bundles (dotnet ef migrations bundle) behave the same way, because they consult the history table.
Scaffolded Down methods mirror Up mechanically. A Down for AddColumn is DropColumn, which deletes every value written since. A Down for migrationBuilder.Sql is empty unless someone wrote it. And they are rarely run in any test, so the first execution is in production under pressure.
migrationBuilder.Sql("...", suppressTransaction: true) step before a failing statement and observe the partial state.A pre-flight check you can run in the pipeline before applying migrations, so data problems fail the build instead of production:
namespace Orders.Deploy;
using Microsoft.EntityFrameworkCore;
public sealed record PreflightResult(bool Ok, string? Reason);
public static class MigrationPreflight
{
// Run against production (read-only login) before applying the migration that adds a unique index.
public static async Task<PreflightResult> CheckUniqueEmailAsync(OrdersDbContext db, CancellationToken ct)
{
var duplicates = await db.Database
.SqlQuery<int>($"""
SELECT COUNT(*) AS [Value] FROM (
SELECT Email FROM Customers WHERE Email IS NOT NULL
GROUP BY Email HAVING COUNT(*) > 1) d
""")
.SingleAsync(ct);
return duplicates == 0
? new PreflightResult(true, null)
: new PreflightResult(false, $"{duplicates} duplicate emails would fail IX_Customers_Email");
}
}
Applying migrations from the pipeline with an idempotent script and a lock timeout:
# Build once, review in the PR, apply the same artefact
dotnet ef migrations script --idempotent --output artefacts/migrate.sql \
--project src/Orders.Infrastructure --startup-project src/Orders.Api
# Apply with a short lock timeout so blocking fails fast instead of piling up
sqlcmd -S "$SQL_SERVER" -d Orders --authentication-method ActiveDirectoryDefault \
-b -Q "SET LOCK_TIMEOUT 5000;" -i artefacts/migrate.sql
Reading the state after a failure:
SELECT TOP (5) MigrationId FROM __EFMigrationsHistory ORDER BY MigrationId DESC;
SELECT name, is_unique FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.Customers');
dotnet ef database update <previous> to execute Down methods. Why it is wrong: Down methods are untested and often drop columns, deleting data written since. Instead: Default to a reviewed forward fix.__EFMigrationsHistory by hand to "skip" a migration. Why it is wrong: History and schema now disagree, and the next migration fails in a confusing way. Instead: Only record a migration once the schema matches it.The best rollback strategy is not needing one. In practice that means three habits: migrations that are backward compatible, so the old app version is always a safe place to retreat to; migrations tested in CI against real SQL Server and rehearsed on a restored, masked production copy, so data problems surface before release; and a monitored run (lock timeout, blocked-session alerts, a person watching) so a problem is stopped in seconds. Everything else in this answer is the fallback for when that discipline slipped.
If a team does rely on Down methods, they must be exercised in the same CI tests as Up (apply, roll back, apply again); otherwise treat them as untested code. I also want the runbook written and rehearsed before the incident, including the measured restore time for our database size. "We can restore" is not a plan; "a restore of our 400 GB database to a new server takes about 90 minutes and we copy back with this script" is.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Redeploy previous app | Schema still compatible | Minutes | New schema broke old code |
| Forward fix migration | Most failures | Time to write and review | Data already destroyed |
| Reviewed, tested Down migration | Trivial additive change | Data in new columns lost | Anything that drops data |
| Point-in-time restore | Data corruption or deletion | Lost writes, switch-over effort | Schema-only failures |
I generate migrations locally with dotnet ef migrations add, then make deployment a separate, reviewed step. The pipeline produces an artefact: either an idempotent SQL script (dotnet ef migrations script --idempotent) for a DBA to review, or a migration bundle (dotnet ef migrations bundle), a self-contained executable that applies pending migrations. That artefact runs once, before the new app version starts, with a dedicated deployment identity. I avoid Database.Migrate() at startup because several instances can race, the app needs DDL permissions it shouldn't have, and a failed migration turns into a crash loop.
dotnet ef migrations bundle builds a single executable (efbundle) that contains your compiled migrations and applies the pending ones to whatever connection string you pass (./efbundle --connection "..."). The target machine needs no .NET SDK, no source and no dotnet-ef tool; with --self-contained -r linux-x64 it does not even need the .NET runtime. It runs migrations idempotently against __EFMigrationsHistory, so it fits a CI/CD release stage or a Kubernetes job. Choose an idempotent SQL script (dotnet ef migrations script --idempotent) instead when a DBA must review and run the SQL, when change control requires the exact statements as an artefact, or when the pipeline cannot reach the database with an executable. Both are better than Database.Migrate() at app start-up.
Apply every migration in CI against a real SQL Server (a Testcontainers container, not the in-memory provider), from an empty database and from the previous release's schema. Then rehearse it in pre-production against a restored, masked copy of production to catch real data problems (duplicates, NULLs, oversized strings) and to time it. Add a CI gate that scans the idempotent script for destructive operations, and a test that dotnet ef migrations has-pending-model-changes returns nothing.
How to tell it (STAR)
**S:** At [company] we released a change that added a unique index on customer email, applied by our pipeline before the slot swap. **T:** The migration step failed and I had to decide how to recover. **A:** I checked the history table and the schema to confirm the failing migration had rolled back and the earlier ones were backward compatible, so production was safe on the old slot. I found [1,200] duplicate emails, wrote a reviewed merge script with the product owner, and re-ran the idempotent script. Then I added pre-flight checks and rehearsal on a production copy. **R:** Customers saw [zero] errors, we shipped [two hours] later, and the pre-flight checks caught [two] similar problems in the following [quarter].
Last updated 23 Nov 2026.