How to set CommandTimeout for DbContext?

Yara picture Yara · May 11, 2012 · Viewed 79.2k times · Source

I am looking a way to set CommandTimeout for DbContext. After searching I found the way by casting DbContext into ObjectContext and setting value for CommandTimeout property of objectContext.

var objectContext = (this.DbContext as IObjectContextAdapter).ObjectContext;

But I have to work with DbContext.

Answer

Jonas Lincoln picture Jonas Lincoln · May 11, 2012

It will work with your method.

Or subclass it (from msdn forum)

public class YourContext : DbContext
{
  public YourContext()
    : base("YourConnectionString")
  {
    // Get the ObjectContext related to this DbContext
    var objectContext = (this as IObjectContextAdapter).ObjectContext;

    // Sets the command timeout for all the commands
    objectContext.CommandTimeout = 120;
  }
}