实体框架和事务范围在释放事务范围后不会还原隔离级别



我对事务范围和实体框架有点了解。

最初,我们希望应用程序中的所有连接在读取数据时都使用快照隔离级别,但在某些情况下,我们希望读取具有已提交读取或未提交读取隔离级别的数据,为此,我们将使用事务范围临时更改查询的隔离级别(如本文和不同博客中的几篇文章所指出的)。

然而,问题是,当事务范围被处理时,隔离仍然保留在连接上,这会导致相当多的问题。

我尝试过所有类型的变体,但结果都是一样的;隔离级别保留在事务范围之外。

有没有人能为我解释这种行为,或者能解释我做错了什么?

我已经找到了解决这个问题的方法,将事务范围封装在一个一次性类中,为我恢复了隔离级别,但我希望能对这种行为做出很好的解释,我认为这种行为不仅会影响我的代码,还会影响其他代码。

以下是说明问题的示例代码:

using (var context = new MyContext())
{
context.Database.Connection.Open();
//Sets the connection to default read snapshot
using (var command = context.Database.Connection.CreateCommand())
{
command.CommandText = "SET TRANSACTION ISOLATION LEVEL SNAPSHOT";
command.ExecuteNonQuery();
}
//Executes a DBCC USEROPTIONS to print the current connection information and this shows snapshot
PrintDBCCoptions(context.Database.Connection);
//Executes a query
var result = context.MatchTypes.ToArray();
//Executes a DBCC USEROPTIONS to print the current connection information and this still shows snapshot
PrintDBCCoptions(context.Database.Connection);
using (var scope = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions()
{
IsolationLevel = IsolationLevel.ReadCommitted //Also tried ReadUncommitted with the same result
}))
{
//Executes a DBCC USEROPTIONS to print the current connection information and this still shows snapshot
//(This is ok, since the actual new query with the transactionscope isn't executed yet)
PrintDBCCoptions(context.Database.Connection);
result = context.MatchTypes.ToArray();
//Executes a DBCC USEROPTIONS to print the current connection information and this has now changed to read committed as expected                    
PrintDBCCoptions(context.Database.Connection);
scope.Complete(); //tested both with and without
}
//Executes a DBCC USEROPTIONS to print the current connection information and this is still read committed
//(I can find this ok too, since no command has been executed outside the transaction scope)
PrintDBCCoptions(context.Database.Connection);
result = context.MatchTypes.ToArray();
//Executes a DBCC USEROPTIONS to print the current connection information and this is still read committed
//THIS ONE is the one I don't expect! I expected that the islation level of my connection should revert here
PrintDBCCoptions(context.Database.Connection);
}

好吧,经过今天的一些挖掘,我发现了一些关于这一点的信息,我将分享这些发现,让其他人知道,并获得意见和建议。

我的问题之所以会取决于环境,有几个原因。

数据库服务器版本:

首先,操作的结果取决于您运行的SQL Server版本(在SQL Server 2012和SQL Server 2014上进行了测试)。

SQL Server 2012

在SQL Server 2012上,上一次设置的隔离级别将在后续操作中跟随连接,即使它被释放回连接池并从其他线程/操作中检索回来。在实践中;这意味着,如果在某个线程/操作中将隔离级别设置为使用事务读取未提交,则连接将保留此级别,直到另一个事务作用域将其设置为另一个隔离级别(或通过对连接执行SET transaction isolation level命令)。不好,你可能会在不知情的情况下突然得到脏的读数。

例如:

Console.WriteLine(context.MatchTypes.Where(mt => mt.Id == 2).Select(mt => mt.LastUpdated).First());
using (var scope = new TransactionScope(TransactionScopeOption.Required, 
new TransactionOptions 
{ 
IsolationLevel = IsolationLevel.ReadUncommitted 
}))
{
Console.WriteLine(context.MatchTypes.Where(mt => mt.Id == 2)
.Select(mt => mt.LastUpdated).First());
scope.Complete(); //tested both with and without
}
Console.WriteLine(context.MatchTypes.Where(mt => mt.Id == 2).Select(mt => mt.LastUpdated).First());

在本例中,第一个EF命令将使用数据库默认值运行,事务范围内的命令将使用ReadUncommitted运行,第三个命令也将使用ReadUncommitted。

SQL Server 2014

另一方面,在SQL Server 2014上,每次从连接池获取连接时,sp_reset_connection过程(看起来就是这个过程)都会将数据库的隔离级别设置回默认级别,即使是从同一事务范围内重新获取连接。在实践中;这意味着,如果您有一个执行两个后续命令的事务作用域,那么只有第一个命令会获得事务作用域的隔离级别。也不好;您将获得(基于数据库上的默认隔离级别)锁定或快照读数。

例如:

Console.WriteLine(context.MatchTypes.Where(mt => mt.Id == 2).Select(mt => mt.LastUpdated).First());
using (var scope = new TransactionScope(TransactionScopeOption.Required, 
new TransactionOptions 
{ 
IsolationLevel = IsolationLevel.ReadUncommitted 
}))
{
Console.WriteLine(context.MatchTypes.Where(mt => mt.Id == 2)
.Select(mt => mt.LastUpdated).First());
Console.WriteLine(context.MatchTypes.Where(mt => mt.Id == 2)
.Select(mt => mt.LastUpdated).First());
scope.Complete(); 
}

在本例中,第一个EF命令将以数据库默认值运行,事务中的第一个命令将以ReadUncommitted运行,但作用域中的第二个命令将突然再次以数据库默认状态运行。

手动打开连接问题:

在手动打开连接的不同SQL Server版本上还会出现其他问题,但是,我们绝对不需要这样做,所以我现在不打算详述这个问题。

使用数据库。BeginTransaction:

出于某种原因,实体框架的Database.BeginTransaction逻辑似乎在两个数据库中都能工作,这是可以的,但在我们的代码中,我们针对两个不同的数据库工作,然后我们需要事务范围。

结论:

我发现SQL Server中这种将隔离级别与事务作用域结合起来的处理非常有缺陷。在这之后,我认为它使用起来不安全,并且可能会在我所看到的任何应用程序中造成严重问题。使用它时要非常谨慎。

但事实仍然存在,我们需要在代码中实现这一点。在最近处理了MS乏味的支持后,我将首先找到一个适用于我们的解决方案。然后,我将使用Connect报告我的发现,并希望微软在事务范围处理和连接方面采取一些措施。

解决方案:

解决方案(就我所知)是这样的。

以下是此解决方案的要求:1.数据库必须在隔离级别中被READ COMMITTED,因为其他应用程序在同一数据库上运行需要这样做,我们不能在数据库上使用READ COMMITTED SNAPSHOT默认值2.我们的应用程序必须具有SNAPSHOT隔离级别的默认值-这可以通过使用SET TRANSACTION ISOLATIONLEVEL SNAPSHOT来解决3.如果有交易范围,我们需要遵守该的隔离级别

因此,基于这些标准,解决方案将是这样的:

在上下文构造函数中,我注册到StateChange事件,当状态更改为Open并且没有活动事务时,我会使用经典的ADO.NET将隔离级别默认为快照。如果使用事务范围,我们需要根据此处的设置运行SET TRANSACTION ISOLATIONLEVEL来遵守此设置(为了限制我们自己的代码,我们将只允许ReadCommitted、ReadUncommitted和Snapshot的ISOLATIONLEVEL)。至于由Database.BeginTransaction在上下文中创建的事务,它似乎得到了应有的尊重,因此我们不对这些类型的事务执行任何特殊操作。

以下是上下文中的代码:

public MyContext()
{
Database.Connection.StateChange += OnStateChange;
}
protected override void Dispose(bool disposing)
{
if(!_disposed)
{
Database.Connection.StateChange -= OnStateChange;
}
base.Dispose(disposing);
}
private void OnStateChange(object sender, StateChangeEventArgs args)
{
if (args.CurrentState == ConnectionState.Open && args.OriginalState != ConnectionState.Open)
{
using (var command = Database.Connection.CreateCommand())
{
if (Transaction.Current == null)
{
command.CommandText = "SET TRANSACTION ISOLATION LEVEL SNAPSHOT";
}
else
{
switch (Transaction.Current.IsolationLevel)
{
case IsolationLevel.ReadCommitted:
command.CommandText = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED";
break;
case IsolationLevel.ReadUncommitted:
command.CommandText = "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";
break;
case IsolationLevel.Snapshot:
command.CommandText = "SET TRANSACTION ISOLATION LEVEL SNAPSHOT";
break;
default:
throw new ArgumentOutOfRangeException();
}
}
command.ExecuteNonQuery();
}
}
}

我已经在SQL Server 2012和2014中测试了这段代码,它似乎可以工作。它不是最漂亮的代码,而且有它的局限性(例如,对于每个EF执行,它总是对数据库执行SET TRANSACTION ISOLATIONLEVEL,从而增加额外的网络流量。)

最新更新