53

I've been receiving an error on one of my pages that the linq query has timed out as it is taking too long. It makes the page unusable.

It's a reports page which is only accessed by administrators around once a day. It's unavoidable to trim this query down at all, it just has to sort through a lot of data.

Solutions to fix this I've read are by increasing the timeout property in the data context, but I'd like to avoid doing that as it would change it for the entire website.

Is there any way to set a larger time out for individual pages?

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456

5 Answers5

81

Just found the answer playing with intellisense:

using (MainContext db = new MainContext())
{
    db.CommandTimeout = 3 * 60; // 3 Mins
}

This is how you can increase the time out for a query on a per query basis as supposed to modifying the connection strings or data contexts.

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
14

@Tom Gullens answer didn't work for me on EF6

I had to drill down to Database on DbContext

Ecom.Database.CommandTimeout = 120;

Hope this saves you some time.

Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265
5

Here is the latest syntax for .Net 4.5.

    MyDbContext context = new MyDbContext();
    context.Database.SetCommandTimeout(300);
ZaneDarken
  • 771
  • 7
  • 9
4

Tom Gullen's answer is a good one.

Another respondent mentioned setting the Connect Timeout in the connection string.
I wanted to caution that the connection timeout property of the connection string is NOT the command timeout. It's more obvious when you think about it. It's a common mistake.

Larry Smith
  • 1,863
  • 16
  • 15
1

Before increasing a SQL timeout it is always worth evaluating your indexing strategy. It is rare, in my experience, that a query against a well indexed table and columns would timeout.

Des Owen

Des Owen
  • 41
  • 4
  • 5
    Hi, welcome to SO. Even if this is very constructive, it's not exactly an answer and should be a comment. You can comment once you earn enough reputation. Cheers! – Cthulhu Apr 04 '16 at 08:51