Set database timeout in Entity Framework
My command keeps timing out, so I need to change the default command timeout value.
I've found myDb.Database.Connection.ConnectionTimeout
, but it's readonly
.
How can I set the command timeout in Entity Framework 5 ?
Solution 1:
Try this on your context:
public class MyDatabase : DbContext
{
public MyDatabase ()
: base(ContextHelper.CreateConnection("Connection string"), true)
{
((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180; // seconds
}
}
If you want to define the timeout in the connection string, use the Connection Timeout
parameter like in the following connection string:
<connectionStrings>
<add name="AdventureWorksEntities"
connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
provider=System.Data.SqlClient;provider connection string='Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient" />
</connectionStrings>
Source: How to: Define the Connection String
Solution 2:
You can use DbContext.Database.CommandTimeout = 180; // seconds
It's pretty simple and no cast required.
Solution 3:
My partial context looks like:
public partial class MyContext : DbContext
{
public MyContext (string ConnectionString)
: base(ConnectionString)
{
this.SetCommandTimeOut(300);
}
public void SetCommandTimeOut(int Timeout)
{
var objectContext = (this as IObjectContextAdapter).ObjectContext;
objectContext.CommandTimeout = Timeout;
}
}
I left SetCommandTimeOut
public so only the routines I need to take a long time (more than 5 minutes) I modify instead of a global timeout.