Skip to content

Commit f16ba9a

Browse files
Document migration locking in applying.md and update cross-references
Agent-Logs-Url: https://github.com/dotnet/EntityFramework.Docs/sessions/a96053e2-50e2-479a-8d0d-fb9bd8bd5c9d Co-authored-by: AndriySvyryd <6539701+AndriySvyryd@users.noreply.github.com>
1 parent 7ed4f3f commit f16ba9a

4 files changed

Lines changed: 88 additions & 3 deletions

File tree

entity-framework/core/managing-schemas/migrations/applying.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,3 +341,78 @@ Note that `MigrateAsync()` builds on top of the `IMigrator` service, which can b
341341
>
342342
> * Carefully consider before using this approach in production. Experience has shown that the simplicity of this deployment strategy is outweighed by the issues it creates. Consider generating SQL scripts from migrations instead.
343343
> * Don't call `EnsureCreatedAsync()` before `MigrateAsync()`. `EnsureCreatedAsync()` bypasses Migrations to create the schema, which causes `MigrateAsync()` to fail.
344+
345+
## Migration locking
346+
347+
Starting with EF Core 9, <xref:Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.MigrateAsync*> and <xref:Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate*> automatically acquire a database-wide lock before applying any migrations. This protects against database corruption that could result from multiple application instances running migrations concurrently, which is a common scenario when [applying migrations at runtime](#apply-migrations-at-runtime). The lock is held for the duration of the migration execution, including any [seeding code](xref:core/modeling/data-seeding#use-seeding-method), and is automatically released when the operation completes.
348+
349+
Migration locking applies when migrations are applied using any of the following methods:
350+
351+
* `dotnet ef database update` (.NET CLI)
352+
* `Update-Database` (Package Manager Console)
353+
* [Migration bundles](#bundles)
354+
* <xref:Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.MigrateAsync*> and <xref:Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate*> (runtime migration)
355+
356+
[SQL scripts](#sql-scripts) are not affected by migration locking, since they are applied outside of EF Core.
357+
358+
> [!NOTE]
359+
> If you are using a third-party database provider, check the provider documentation to understand the locking behavior specific to your database. The information below covers the SQL Server and SQLite providers included with EF Core.
360+
361+
### How the lock works
362+
363+
The locking mechanism is provider-specific:
364+
365+
* **SQL Server** uses `sp_getapplock` to acquire a session-level application lock named `__EFMigrationsLock`. This lock is automatically released when the database connection is closed, so it cannot become abandoned even if the application terminates unexpectedly.
366+
* **SQLite** does not have a built-in application locking mechanism, so EF Core creates a `__EFMigrationsLock` table and uses it to coordinate access. A row is inserted to acquire the lock and deleted to release it. This lock requires explicit release (see [Handling abandoned locks](#handling-abandoned-locks)).
367+
368+
If another migration execution is already in progress, the new request waits until the lock becomes available.
369+
370+
### Handling abandoned locks
371+
372+
In most cases, the migration lock is released automatically when the operation completes or when the connection is closed. However, on **SQLite**, if the application terminates unexpectedly (for example, the process is killed during migration), the lock row in the `__EFMigrationsLock` table may not be cleaned up. This prevents any subsequent migration from completing, because each attempt will wait indefinitely for the lock to be released.
373+
374+
To resolve an abandoned lock on SQLite, delete the `__EFMigrationsLock` table from the database:
375+
376+
```sql
377+
DROP TABLE "__EFMigrationsLock";
378+
```
379+
380+
Or, alternatively, delete all rows from the table:
381+
382+
```sql
383+
DELETE FROM "__EFMigrationsLock";
384+
```
385+
386+
After clearing the lock, subsequent migration operations proceed normally. The table is automatically recreated as needed.
387+
388+
> [!NOTE]
389+
> This issue is specific to the SQLite provider. On SQL Server, the lock is session-based and is automatically released when the connection closes, so abandoned locks are not a concern.
390+
391+
### Migrations and explicit transactions
392+
393+
Starting with EF Core 9, calling <xref:Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.MigrateAsync*> inside an explicit transaction throws a warning by default. This is because wrapping migrations in an external transaction prevents the migration lock from being acquired, which leaves the database unprotected from concurrent migration applications. EF Core manages its own transactions internally as needed during migration.
394+
395+
If you were previously wrapping `MigrateAsync()` in an explicit transaction:
396+
397+
```csharp
398+
// This will throw a warning in EF Core 9+
399+
await strategy.ExecuteAsync(async () =>
400+
{
401+
await using var transaction = await dbContext.Database.BeginTransactionAsync();
402+
await dbContext.Database.MigrateAsync();
403+
await transaction.CommitAsync();
404+
});
405+
```
406+
407+
Remove the external transaction and `ExecutionStrategy`:
408+
409+
```csharp
410+
// Recommended: let EF Core manage transactions
411+
await dbContext.Database.MigrateAsync();
412+
```
413+
414+
If your scenario requires an explicit transaction and you have another mechanism in place to prevent concurrent migration application, you can suppress the warning:
415+
416+
```csharp
417+
options.ConfigureWarnings(w => w.Ignore(RelationalEventId.MigrationsUserTransactionWarning))
418+
```

entity-framework/core/modeling/data-seeding.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ There are several ways this can be accomplished in EF Core:
2121

2222
## Configuration options `UseSeeding` and `UseAsyncSeeding` methods
2323

24-
EF 9 introduced <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> and <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseAsyncSeeding*> methods, which provide a convenient way of seeding the database with initial data. These methods aim to improve the experience of using custom initialization logic (explained below). They provide one clear location where all the data seeding code can be placed. Moreover, the code inside <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> and <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseAsyncSeeding*> methods is protected by the [migration locking mechanism](/ef/core/what-is-new/ef-core-9.0/whatsnew#concurrent-migrations) to prevent concurrency issues.
24+
EF 9 introduced <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> and <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseAsyncSeeding*> methods, which provide a convenient way of seeding the database with initial data. These methods aim to improve the experience of using custom initialization logic (explained below). They provide one clear location where all the data seeding code can be placed. Moreover, the code inside <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> and <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseAsyncSeeding*> methods is protected by the [migration locking mechanism](xref:core/managing-schemas/migrations/applying#migration-locking) to prevent concurrency issues.
2525

2626
The new seeding methods are called as part of <xref:Microsoft.EntityFrameworkCore.Storage.IDatabaseCreator.EnsureCreated*> operation, <xref:Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate*> and `dotnet ef database update` command, even if there are no model changes and no migrations were applied.
2727

entity-framework/core/providers/sqlite/limitations.md

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,17 @@ dotnet ef database update --connection "Data Source=My.db"
9292

9393
## Concurrent migrations protection
9494

95-
EF9 introduced a locking mechanism when executing migrations. It aims to protect against multiple migration executions happening simultaneously, as that could leave the database in a corrupted state. This is one of the potential problems resulting from applying migrations at runtime using the <xref:Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate%2A> method (see [Applying migrations](xref:core/managing-schemas/migrations/applying) for more information). To mitigate this, EF creates an exclusive lock on the database before any migration operations are applied.
95+
EF9 introduced a [migration locking mechanism](xref:core/managing-schemas/migrations/applying#migration-locking) when executing migrations. It aims to protect against multiple migration executions happening simultaneously, as that could leave the database in a corrupted state. This is one of the potential problems resulting from applying migrations at runtime using the <xref:Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate%2A> method (see [Applying migrations](xref:core/managing-schemas/migrations/applying) for more information). To mitigate this, EF creates an exclusive lock on the database before any migration operations are applied.
9696

97-
Unfortunately, SQLite does not have built-in locking mechanism, so EF Core creates a separate table (`__EFMigrationsLock`) and uses it for locking. The lock is released when the migration completes and the seeding code finishes execution. However, if for some reason migration fails in a non-recoverable way, the lock may not be released correctly. If this happens, consecutive migrations will be blocked from executing SQL and therefore never complete. You can manually unblock them by deleting the `__EFMigrationsLock` table in the database.
97+
Unfortunately, SQLite does not have a built-in application locking mechanism, so EF Core creates a separate table (`__EFMigrationsLock`) and uses it for locking. A row is inserted to acquire the lock and deleted to release it when the migration completes and the seeding code finishes execution. However, if the application terminates unexpectedly during migration (for example, the process is killed), the lock may not be released. If this happens, subsequent migration attempts will wait indefinitely for the lock.
98+
99+
To resolve an abandoned lock, delete the `__EFMigrationsLock` table or its rows from the database:
100+
101+
```sql
102+
DROP TABLE "__EFMigrationsLock";
103+
```
104+
105+
For more information, see [Handling abandoned locks](xref:core/managing-schemas/migrations/applying#handling-abandoned-locks).
98106

99107
## See also
100108

entity-framework/core/what-is-new/ef-core-9.0/whatsnew.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1088,6 +1088,8 @@ The above were only some of the more important query improvements in EF9; see [t
10881088

10891089
EF9 introduces a locking mechanism to protect against multiple migration executions happening simultaneously, as that could leave the database in a corrupted state. This doesn't happen when migrations are deployed to the production environment using [recommended methods](/ef/core/managing-schemas/migrations/applying#sql-scripts), but can happen if migrations are applied at runtime using the [`DbContext.Database.MigrateAsync()`](/dotnet/api/microsoft.entityframeworkcore.relationaldatabasefacadeextensions.migrate) method. We recommend applying migrations at deployment, rather than as part of application startup, but that can result in more complicated application architectures (e.g. [when using .NET Aspire projects](/dotnet/aspire/database/ef-core-migrations)).
10901090

1091+
For more information, see [Migration locking](/ef/core/managing-schemas/migrations/applying#migration-locking).
1092+
10911093
> [!NOTE]
10921094
> If you are using Sqlite database, see [potential issues associated with this feature](/ef/core/providers/sqlite/limitations#concurrent-migrations-protection).
10931095

0 commit comments

Comments
 (0)