Search code examples
c#asp.netlinqlinq-to-entitiessql-server-profiler

Linq to Entities query hitting db twice


I have the following pretty simple linq query querying a linq to entities edmx.

(from i in ent.Inspectors select i).OrderBy(s => s.Surname).Skip((page - 1) * count).Take(count).ToList();

In Sql Server Profiler I can see that the exact same select query is being sent twice.

Can someone explain why?

Cheers,

Dave


Solution

  • Because of deffered execution, the results of the query aren't cached locally. To prevent this, add a call to ToArray in the query.

    Also, from i in ent.Inspectors select i is a no-op; you should write ent.Inspectors.OrderBy(s => s.Surname)....