You have a long running Entity Framework query that often creates a “System.Data.SqlClient.SqlException” with the message “Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.”
As near as I can find, the default timeout for EF queries using the SQL Server 2008 connection provider is 30 seconds. If your query runs longer than that, you are going to get the error above.
If you are using dbContext, the solution to this is to add the following code before your query to set the timeout to a longer value:
((IObjectContextAdapter)Context).ObjectContext.CommandTimeout = 180;
Of course, you can use any number of seconds you need. This line of code moves you down from dbContext to the underlying ObjectContext to make the change.
I’m not sure why Microsoft didn’t keep the simpler syntax from the older version of ObjectContext for dbContext. If you are using ObjectContext, you can do without the adapter, like this:
this.Context.CommandTimeout = 180;
To keep from having to put this code in every query, you could call it when you instantiate the dbContext. You may find it helpful to keep the default timeout for most queries and catch the error to give you insight into database problems.
3 thoughts on “How To Extend the Timeout Period on an Entity Framework Query”
you are a true lifesaver, I spent hours trying to figure out why an inherited project kept on crashing with a timeout.
To change it outside the autogenerated code I entered the following:
MyEntities db = new MyEntities();
IObjectContextAdapter dbcontextadapter = (IObjectContextAdapter)db;
dbcontextadapter.ObjectContext.CommandTimeout = 180;
var result = (from i in db.MyStoredPRocedureCall(Param1, Param2)
This way, I don’t lose the timeout code when I regenerate the autogenerated code.
That’s exactly how I’m using it, too. I put it in my repositories before a long-running query.