title: Linq. Help me tune this!
body: <p>I have a linq query that is causing some timeout issues. Basically, I have a query that is returning the top 100 results from a table that has approximately 500,000 records.</p>
  
  <p>Here is the query:</p>
  
  <pre><code>using (var dc = CreateContext())
          {
              var accounts = string.IsNullOrEmpty(searchText)
                              ? dc.Genealogy_Accounts
                                  .Where(a =&gt; a.Genealogy_AccountClass.Searchable)
                                  .OrderByDescending(a =&gt; a.ID)
                                  .Take(100)
                              : dc.Genealogy_Accounts
                                  .Where(a =&gt; (a.Code.StartsWith(searchText)
                                              || a.Name.StartsWith(searchText))
                                              &amp;&amp; a.Genealogy_AccountClass.Searchable)
                                  .OrderBy(a =&gt; a.Code)
                                  .Take(100);
              return accounts.Select(a =&gt; 
          }
      }
  </code></pre>
  
  <p>Oddly enough it is the first linq query that is causing the timeout. I thought that by doing a 'Take' we wouldn't need to scan all 500k of records. However, that must be what is happening. I'm guessing that the join to find what is 'searchable' is causing the issue. I'm not able to denormalize the tables... so I'm wondering if there is a way to rewrite the linq query to get it to return quicker... or if I should just write this query as a Stored Procedure (and if so, what might it look like). Thanks.</p>