Skip to content

Explicit Database.BeginTransaction vs ambient transaction. #1110

Open

Description

@voroninp

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:

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.

Activity

  1. added this to the Backlog milestone on Sep 2, 2019
  2. limup commented on Oct 10, 2022

    @limup

    I've got the same error. Any idea how the fix them?

  3. roji commented on Oct 10, 2022

    @roji
    Member

    @voroninp this restriction doesn't really have anything to do with EF Core - you're effectively asking to start two transactions on the same connection, and that's not supported at the low-level driver layer. As always, there's a documentation balance to be struck, where detailing each and every possible not-supported pattern is detrimental in general. And in any case, any user attempting to do this would immediately get an informative exception telling them that this isn't supported, so I'm not sure what value a doc not would have here.

    @limup you must either use TransactionScope or BeginTransaction, but not both.

  4. limup commented on Oct 11, 2022

    @limup

    @voroninp this restriction doesn't really have anything to do with EF Core - you're effectively asking to start two transactions on the same connection, and that's not supported at the low-level driver layer. As always, there's a documentation balance to be struck, where detailing each and every possible not-supported pattern is detrimental in general. And in any case, any user attempting to do this would immediately get an informative exception telling them that this isn't supported, so I'm not sure what value a doc not would have here.

    @limup you must either use TransactionScope or BeginTransaction, but not both.

    Ok, I understood now. Thank you for answer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions