【问题标题】:Transaction scope issue in Entity Framework实体框架中的事务范围问题
【发布时间】:2016-10-01 02:49:16
【问题描述】:
与当前连接关联的事务已完成但尚未处理。必须先释放事务,然后才能使用连接执行 SQL 语句
当我尝试在事务中通过 EF6 保存时,出现上述错误。
我正在更新表中的数据,并且我有一个更新该表的触发器。因此,当我禁用触发器时,一切正常,但是当我启用触发器时,我得到了上述错误。
我尝试增加超时和抑制交易,但没有成功..
我的交易代码如下所示:
using (TransactionScope transaction = new TransactionScope())
{
var obj = this._objRepo.GetobjCodesByName("xxxxxx");
obj.CodeName = "eeee";
this._context.SaveChanges();
transaction.Complete();
return Code;
}
有什么解决方法吗?
【问题讨论】:
标签:
sql-server
c#-4.0
entity-framework-6
transactionscope
【解决方案1】:
这里你根本不需要使用事务。因为你只有一个事务。那么你不需要使用TransactionScope()。如果你没有必要使用它,它会给你带来额外的开销保存过程。换句话说,它会导致操作变慢。
不使用TransactionScope()可以尝试如下图。
using (var _context= new YourDBEntities())
{
//your update code
_context.SaveChanges();
}
【解决方案2】:
我不知道代码的全部范围。但是根据您问题中发布的代码 sn-p ,问题出在_objRepo.GetobjCodesByName("xxxxxx");
您需要禁止在事务范围内进行选择。在 SQL Server 2005 及更高版本中,即使您使用 with(nolock),仍然会在 select 触及的那些表上创建锁。
为了解决这种情况,你需要重写代码如下
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;
}
希望这会有所帮助。