I have read that when a DbContext.SaveChanges() runs all the operations are automatically wrapped in a transaction for you behind the scenes. That is, if any of the operations inside during SaveChanges() fail, everything is rolled back maintaining consistent state.
However, one term I've come across several times is that the changes can run as part of an ambient transaction. What exactly does that mean?
My specific concern is: I have a multithreaded application, in which I have one context per operation. None of my DbContext objects are shared across different threads. Am I guaranteed that the operations of each DbContext.SaveChanges() will run in separate transactions?
In your case, yes, you are guaranteed that each DbContext.SaveChanges() will run in separate transactions.
The term "ambient" transaction refers to a transaction that was started higher-up in the call stack. So that this is a per-thread concept. See Transaction.Current and TransactionScope. It is a feature that allows you do to something like this:
using (TransactionScope scope123 = new TransactionScope())
{
using (SqlConnection connection1 = new SqlConnection(connectString1))
{
// Do some work
using (SqlConnection connection2 = new SqlConnection(connectString2))
{
// Do some more work
}
}
Both of the above connections automatically use the "ambient" transaction "scope123." It sounds like the entity framework now knows how to do this. But the TransactionScope won't cross threads, so you are okay. And it doesn't sound like you are explicitly creating transaction scopes anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With