Database Reference
In-Depth Information
Listing 14-7. Creating Nested TransactionScopes and Setting the IsolationLevel to ReadUncommitted
using (var context = new EF6RecipesContext())
{
using (var scope1 = new TransactionScope())
{
// save, but don't commit
var outerEmp = new Employee { Name = "Karen Stanfield" };
Console.WriteLine("Outer employee: {0}", outerEmp.Name);
context.Employees.Add(outerEmp);
context.SaveChanges();
// second transaction for read uncommitted
using (var innerContext = new EF6RecipesContext())
{
using (var scope2 = new TransactionScope(
TransactionScopeOption.RequiresNew,
new TransactionOptions {
IsolationLevel = IsolationLevel.ReadUncommitted }))
{
var innerEmp = innerContext.Employees
.First(e => e.Name == "Karen Stanfield");
Console.WriteLine("Inner employee: {0}", innerEmp.Name);
scope1.Complete();
scope2.Complete();
}
}
}
}
The following is the output of the code in Listing 14-7:
Outer employee: Karen Stanfield
Inner employee: Karen Stanfield
How It Works
In SQL, one of the common ways of reading uncommitted data is to use the NOLOCK query hint. However, Entity
Framework does not support the use of hints. In Listing 14-7, we used a TransactionScope with the IsolationLevel set
to ReadUncommitted . This allowed us to read the uncommitted data from the outer TransactionScope. We did this in a
fresh data context.
 
Search WWH ::




Custom Search