Answer the question
In order to leave comments, you need to log in
Explain the connection pool and transactions in EF and SQL Server - why is it written in the links?
Here https://coderwall.com/p/jnniww/why-you-shouldn-tu... they write:
Here we go, since DbContext use the same connection string , a connection we get is the same connection returned from connection pool, therefore we run into the ambient transaction and see partial data which has not been fixed in database yet.
No, this was a coincidence because the 2nd context reused the connection of the 1st from the connection pool. This is not guaranteed and will break under load.
you're right, this doesn't work if you use one DbContext instance for multiple threads.
I never run into the problem that the connection pool was an issue. Every DbContext instance is associated with a single connection (standard settings). No matter what you do, the DbContext will reset the connection on dispose so that it can be used again by other consumers.
Answer the question
In order to leave comments, you need to log in
It is very easy to check - run SQL Server Profiler and see the SPID under which requests come to the server. If SPID are different then the sessions are different.
If SPID are different then the sessions are different.
using (var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions {IsolationLevel = IsolationLevel.Snapshot}))
{
var data1Id;
using (var dbContext = new DB())
{
var data1= new Data1();
dbContext.Table1.Add(data1);
/*1*/dbContext.SaveChanges();
data1Id = data1.Id;
}
if (data1Id != 0)
{
using (var transactionScope2 = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions {IsolationLevel = IsolationLevel.Snapshot}))
{
using (var dbContext = new DB())
{
dbContext.Table2.Add(new Data2() { Data1Id = data1Id, ... });
/*2*/dbContext.SaveChanges();
transactionScope2.Complete();
}
}
}
transactionScope.Complete();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question