Using code like
using (var tran = Ctxt.Database.BeginTransaction()) {
How can I set a value for the transaction timeout ?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With