Search for existing suggestions

Use ambient transaction for queries similar to how it's used for SaveChanges

SaveChanges will use the ambient transaction if present but queries will not. This effectively prevents consistency without using BeginTransaction, UseTransaction or opening the connection outside of EF and passing it in. These three options would work but make for a much less cleaner design than would be permitted by effective usage of TransactionScope. As it stand, TransactionScope cannot be used as long as only SaveChanges will use the ambient transaction.

1 vote
Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)

We’ll send you updates on this idea

Andrei Pacurariu shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

EF6.x and previous versions of EF use ambient transactions for queries: By default a database connection is opened to execute the query and that connection is automatically enlisted in an ambient transaction if present. That is how it works for both query and SaveChanges(). The main difference is that while in SaveChanges() we call BeginTransaction() to create a database transaction when there is not ambient transaction present.

2 comments

Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
Submitting...
  • Andrei Pacurariu commented  ·   ·  Flag as inappropriate

    Hi Diego!

    Thank you for your quick response! Thanks for clarifying that - I knew previous versions did but was unsure of the latest version of EF6.
    I've tested it out again and it works perfectly.

    Originally I had a small issue which made it look as if it doesn't use the ambient transaction.
    When I tried to debug it I used the IDbCommandInterceptor and IDbTransactionInterceptor and also looked at Context.Database.CurrentTransaction and all of them showed the transaction as null.
    This confused me and led me to believe that EF6 no longer uses the ambient transaction.
    The docs confused me further saying that "Entity Framework does not wrap queries in a transaction." - I obviously interpreted this incorrectly.

    My bad! Thanks for clarifying.

    Regards.

Feedback and Knowledge Base