如何在Entity Framework 6 DbContext.Database.BeginTransaction中配置事务超时时间?

9
使用类似以下的代码
using (var tran = Ctxt.Database.BeginTransaction()) {   

如何设置事务超时的值?
2个回答

6

如果由于某种原因您需要自己管理事务,使用 TransactionScope 将会更加容易。它有几个构造函数可接受 TimeSpan 参数来设置超时时间。例如:

using(var ts = new TransactionScope(TransactionScopeOption.Required,
                                    TimeSpan.FromMinutes(1)))
{
    using(var ctx = new MyContext())
    {
        // Do stuff.
    }
    ts.Complete(); // Try - catch to catch TimeoutException
}

我很好奇您为什么想设置事务超时而不是命令超时。

3
请告诉我,Entity Framework 中默认的事务超时时间是多少? - habib
使用TransactionScope和MS SQL Server时,我遇到了以下错误:_与当前连接相关联的事务已经完成但没有被处理_。但在Oracle中不会出现这种情况。如果我使用DbContext.BeginTransaction,则两个数据库都可以正常工作。 - Matej

4

我的建议是使用Database.CommandTimeout

var timeout = 60; //or whatever value you need
Ctxt.Database.CommandTimeout = timeout;
using (var tran = Ctxt.Database.BeginTransaction())
{
    //do stuff
}
//this line can be skipped if you're about to dispose context
Ctxt.Database.CommandTimeout = null; //setting back default timeout

当然,你可以把它包裹在一个类中。

1
CommandTimeout 是针对单个命令的持续时间。 一个事务范围可以有多个命令。 因此 @GertArnold 的答案是正确的。 - GregJF
1
@GertArnold的回答提供了一种替代方案,但从技术上讲并没有回答这个问题。 - Suncat2000

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接