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 ?
This question is related to
c#
.net
asp.net-mvc
entity-framework
connection-timeout
For Database first Aproach:
We can still set it in a constructor, by override the ContextName.Context.tt T4 Template this way:
<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{
public <#=code.Escape(container)#>()
: base("name=<#=container.Name#>")
{
Database.CommandTimeout = 180;
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
this.Configuration.LazyLoadingEnabled = false;
<#
}
Database.CommandTimeout = 180;
is the acutaly change.
The generated output is this:
public ContextName() : base("name=ContextName")
{
Database.CommandTimeout = 180;
}
If you change your Database Model, this template stays, but the actualy class will be updated.
In the generated constructor code it should call OnContextCreated()
I added this partial class to solve the problem:
partial class MyContext: ObjectContext
{
partial void OnContextCreated()
{
this.CommandTimeout = 300;
}
}
You can use this simple
:dbContext.Database.SetCommandTimeout(300);
You can use DbContext.Database.CommandTimeout = 180; // seconds
It's pretty simple and no cast required.
I extended Ronnie's answer with a fluent implementation so you can use it like so:
dm.Context.SetCommandTimeout(120).Database.SqlQuery...
public static class EF
{
public static DbContext SetCommandTimeout(this DbContext db, TimeSpan? timeout)
{
((IObjectContextAdapter)db).ObjectContext.CommandTimeout = timeout.HasValue ? (int?) timeout.Value.TotalSeconds : null;
return db;
}
public static DbContext SetCommandTimeout(this DbContext db, int seconds)
{
return db.SetCommandTimeout(TimeSpan.FromSeconds(seconds));
}
}
I just ran in to this problem and resolved it by updating my application configuration file. For the connection in question, specify "Connection Timeout=60" (I am using entity framework version 5.0.0.0)
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.
Same as other answers, but as an extension method:
static class Extensions
{
public static void SetCommandTimeout(this IObjectContextAdapter db, TimeSpan? timeout)
{
db.ObjectContext.CommandTimeout = timeout.HasValue ? (int?) timeout.Value.TotalSeconds : null;
}
}
Source: Stackoverflow.com