dotnet / dotnet/EntityFramework.Docs

Explicit Database.BeginTransaction vs ambient transaction.

Open
#1,110 3 comments 0 reactions 0 assignees View on GitHub
area-transactions
Dominant language
Mermaid
Stars
1.7k
Forks
2k
Avg merge
7d 23h
Merged PRs (30d)
16

Description

It should be mentioned that explicitly starting a database transaction via call `DbContext.Database.BeginTransaction()` will lead to exception if it is done inside ambient transaction scope.

The thrown exception is:
> System.InvalidOperationException: 'An ambient transaction has been detected. The ambient transaction needs to be completed before beginning a transaction on this connection.'

Code:
```CSharp
using (var ambientTxn = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
using (var txn = await context.Database.BeginTransactionAsync())
{
}
```

---
#### Document Details

⚠ *Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.*

* ID: 1073c238-9389-d826-a696-f1108a4f2ce0
* Version Independent ID: cf56babd-def0-d76e-8eee-e33341b6a009
* Content: [Transactions - EF Core](https://docs.microsoft.com/en-us/ef/core/saving/transactions#feedback)
* Content Source: [entity-framework/core/saving/transactions.md](https://github.com/aspnet/EntityFramework.Docs/blob/master/entity-framework/core/saving/transactions.md)
* Product: **entity-framework**
* GitHub Login: @rowanmiller
* Microsoft Alias: **divega**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.