![](/img/trans.png)
[英]Behavior of unit of work + entity framework + transaction without explicit rollback on exception
[英]Unit Of Work inside Transaction scope and Entity Framework
当我尝试在TransactionScope
保存实体时出现异常,我得到的异常是:
The operation is not valid for the state of the transaction
但是在另一台机器上,我在同一个代码块上得到了一个不同的异常:
The transaction operation cannot be performed because there are pending requests working on this transaction
我的方法中的事务实现是:
TransactionHelper.Transaction(() =>
{
if (sys.WfId.HasValue)
{
var sysData = GeneralMapping.GetSysData(model, ThisUser);
DoAction(sys, model, sysData);
if (!_sysClosed)
{
_Repository.InsertOrUpdate(sys);
_Uow.Save();
}
}
});
TransactionHelper :
public static class TransactionHelper
{
public static void HandleTransaction(Action action)
{
using (var tx = CreateScope())
{
action();
tx.Complete();
}
}
private static TransactionScope CreateScope(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
{
var tOptions = new TransactionOptions
{
IsolationLevel = isolationLevel,
Timeout = TransactionManager.MaximumTimeout
};
return new TransactionScope(TransactionScopeOption.Required, tOptions);
}
}
这完全没有任何问题,但是最近在我开始看到这些异常之后,我被告知这个实现可能会导致死锁,因为工作单元是事务中的事务(Business Transaction - Martin Fowler )范围,这可能是原因吗? 如果需要,如果需要,可以采用哪种替代方案?
某些原因发生了这种异常,例如事务超时,在彼此内部嵌套两个事务,在事务范围内部有两个开放连接,对整个Web应用程序使用单个DbContext
实例,因此DbContext拥有它自己的UOF,它可能会在主题之间发生一些冲突原因。 您可以使用System.Transactions.Transaction.Current.TransactionInformation.Status
来识别事务的状态,并在抛出异常之前将其中止。
更改return new TransactionScope(TransactionScopeOption.Required, tOptions);
return new TransactionScope(TransactionScopeOption.RequiresNew, tOptions);
并再次测试它,看看会发生什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.