How To Extend the Timeout Period on an Entity Framework Query

The Situation:

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.”

A Solution:

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

  1. 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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s