Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you configure the Transaction time out in Entity Framework 6 DbContext.Database.BeginTransaction?

Using code like

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

How can I set a value for the transaction timeout ?

like image 944
John Waters Avatar asked Oct 15 '13 23:10

John Waters


People also ask

How do I increase command timeout in Entity Framework?

In your code, instantiate the Container class and if you need to use a custom timeout for a specific command, set it manually using the provided methods. using (var db = new MyEntitiesContainer()) { db. SetCommandTimeout(300); db. DoSomeLongCommand(); db.

What is the default Entity Framework timeout?

Sometimes, however, you might also want to include a task that requires longer than the default command timeout value (30 seconds in SQL Server) such as importing a lot of data.

How does Entity Framework maintain transactions?

Entity Framework internally maintains transactions when the SaveChanges() method is called. It means the Entity Framework maintains a transaction for the multiple entity insert, update and delete in a single SaveChanges() method. When we execute another operation, the Entity Framework creates a new transaction.


1 Answers

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.

like image 70
Gert Arnold Avatar answered Oct 15 '22 23:10

Gert Arnold