9

Using code like

using (var tran = Ctxt.Database.BeginTransaction()) {   

How can I set a value for the transaction timeout ?

Eric J.
  • 147,927
  • 63
  • 340
  • 553
John Waters
  • 689
  • 2
  • 8
  • 16

2 Answers2

6

If for whatever reason you need to manage transactions yourself it is much easier to use TransactionScope. It has several constructors accepting a TimeSpan parameter to set the timeout. For instance

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

I'm curious though why you want to set transaction timeout, not command timeout.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • 3
    please tell me what is the default transaction timeout in entity framework? – habib Jun 28 '18 at 03:32
  • When using TransactionScope with MS SQL Server, I get the following error: _The transaction associated with the current connection has completed but has not been disposed_. It does not happen with Oracle. If I use DbContext.BeginTransaction, it works with both databases. – Matej Sep 29 '21 at 08:43
4

My suggestion would be to use 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

Of course, you can nicely wrap it in some class.

Grengas
  • 836
  • 12
  • 16
  • 1
    CommandTimeout is for the duration of a single command A transaction scope can have multiple commands Therefore @GertArnold answer is correct – GregJF Apr 16 '18 at 04:12
  • 1
    @GertArnold's answer offers an alternative, but technically it doesn't answer the question. – Suncat2000 May 01 '20 at 19:07