How to configure transaction timeout in Entity Framework 6 DbContext.Database.BeginTransaction?

Using type code

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

How to set value for transaction timeout?

+6
source share
2 answers

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 beautifully wrap it in some class.

+3
source

If for any reason you need to manage your transactions yourself, it’s much easier to use TransactionScope . It has several constructors that accept a TimeSpan parameter to set a 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 am curious why you want to set the transaction timeout, not the command timeout.

+1
source

Source: https://habr.com/ru/post/956031/


All Articles