The Self-Taught Programmer

Recipes from real-world experience with asp.net.

Posts Tagged ‘dbContext

How To Extend the Timeout Period on an Entity Framework Query

with 3 comments

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.

Advertisements

Written by Jim McMullen

July 28, 2013 at 3:16 pm

Posted in How-To

Tagged with , ,