1

I have a piece of code that is selecting based on dates, using an IQueryable. The sql performance here is causing timeouts. If this was straight SQL, I'd using (OPTIMIZE FOR (@date UNKNOWN). However, with

DateTime now = DateTime.UTC Now;

var results = from item in items.Find()
where item.startDate <= now
where item.endDate > now 
select item;

return results;

Is there a good way to add this hint? Or should I move this to the database as a stored procedure?

Feasoron
  • 3,471
  • 3
  • 23
  • 34
  • I don't think that code will compile – Selman Genç Jan 29 '14 at 16:30
  • It's not the exact code, I pulled it out and changed the variable names to simplify it. The code we has does compile and has been running for some time now. I'll clean it up to make it a little clearer, though. – Feasoron Jan 29 '14 at 16:32
  • This is a simple query to stuck in the sql server. Have you set correct indexes? What is selectivity of that columns? Why do you use `Find()` without key? It will be all your items to store then filter them by predicate. – Hamlet Hakobyan Jan 29 '14 at 16:59

2 Answers2

1

I don't see how hints are going to help you with performance here. You should first get your query right and see the SQL that is generated by Entity Framework on a SQL profiler. The following snippet should give a decent performance if your database is designed as i expect it is.

var results = item.Where(x=> x.startDate <= now && x.endDate > now)

Check out this related question for index hints on sql server, summarizing, can't use them with linq.

How do I get LinqToSql to pass “index hints” to sql server?

Community
  • 1
  • 1
Andrei Dvoynos
  • 1,126
  • 1
  • 10
  • 32
1

Assumptions: Find() returns an IQueryable and there are indexes on startDate and endDate

I don't know of a way to add query hints to Linq since they're provider specific, but you could try a few things:

use && instead of multiple where clauses:

DateTime now = DateTime.UTCNow;
var results = from item in items.Find()
              where item.startDate <= now 
                 && item.endDate > now 
              select item;

Execute straight SQL via ExecuteStoreQuery:

string sql = @"SELECT * FORM Items " + 
              "WHERE startDate <= @asOf
              "  AND endDate > @asOf"
var results = db.ExecuteStoreQuery<Item>(sql, new [] {now});
D Stanley
  • 149,601
  • 11
  • 178
  • 240