实体框架中的事务范围问题

时间:2016-10-01 02:49:16

标签: sql-server c#-4.0 entity-framework-6 transactionscope

  

与当前连接关联的交易已完成但尚未处置。必须先处理事务,然后才能使用连接执行SQL语句

当我尝试在事务中通过EF6保存时,我收到了上述错误。 我正在更新表中的数据,我有一个触发更新该表。所以,当我禁用触发器时一切正常,但是当我启用触发器时,我得到上面提到的错误。

我尝试增加超时抑制交易,但没有运气..

我的交易代码如下所示:

using (TransactionScope transaction = new TransactionScope())
{
    var obj = this._objRepo.GetobjCodesByName("xxxxxx");
    obj.CodeName = "eeee";

    this._context.SaveChanges();
    transaction.Complete();

    return Code;
}

任何解决方法?

2 个答案:

答案 0 :(得分:0)

此处您根本不需要使用交易.B'因为您只有一笔交易。然后您不需要使用TransactionScope()。如果您不需要使用,它会为您的保存过程带来额外的开销。换句话说,它会导致操作变慢。

您可以尝试如下所示,而不使用TransactionScope()

using (var _context= new YourDBEntities())
{
   //your update code

   _context.SaveChanges();
}   

答案 1 :(得分:0)

我不知道代码的全部范围。但根据您问题中发布的代码段,问题出在_objRepo.GetobjCodesByName("xxxxxx");

您需要禁止从事务范围中进行选择。在SQL Server 2005及更高版本中,即使使用(nolock),仍然会在这些表上创建锁定选择触摸。

要解决这种情况,您需要重写以下代码

using (TransactionScope transaction = new TransactionScope())
{
    using(TransactionScope tsSuppressed = new TransactionScope(TransactionScopeOption.Suppress)) 
    {
        var obj = this._objRepo.GetobjCodesByName("xxxxxx");
        obj.CodeName = "eeee";
    }

    this._context.SaveChanges();
    transaction.Complete();

    return Code;
}

希望这有帮助。