I am developing an MVC website that uses the Entity Framework. I am an ex ADO.Net forms man, so it’s all a bit new to me. My EDM currently consists of an abstract “Product” Entity, which has 5 different “type” Entities that inherit from it. The “Product” Entity maps to 7 or 8 tables and has about 50 properties, each “type” that inherits from a “Product” has some 5 to 20 extra properties that extend a “Product”. I notice that when I used the .Take extension method on the IQueryable to return data to a Telerik grid, it was taking noticably longer to return data than if I just greedily returned the whole collection to memory using .ToList.
When I ran SQL Profiler to see just what the devil was going on, here is what I found.
exec sp_executesql N'SELECT TOP (20)
[Project12].[C1] AS [C1],
[Project12].[C2] AS [C2],
[Project12].[C3] AS [C3],
etc ... 508 SQL lines follow, too much to paste here unfortunately.
Takes 500 milliseconds to execute. The following however:
exec sp_executesql N'SELECT
[Project12].[C1] AS [C1],
[Project12].[C2] AS [C2],
[Project12].[C3] AS [C3],
etc ...
Takes around 80 milliseconds to execute.
So, judging by the above logic, I should ditch deferred execution, and every time the user changes page… take the entire dataset down into memory (500 rows or so). Does anyone have any suggestions what is going on and why SQL Server 2005 is behaving in this way?
EDIT
I’ve placed the full SQL on http://pastebin.com/rAGGSScA . Could it be that SQL is caching the “full” select, and not caching the “TOP (20)” results?
Client Statistics for SELECT

Client Statistics for SELECT TOP (20)

Somewhere in your “508 SQL lines [that] follow” will be an ORDER BY clause. By forcing a “TOP (N)” evaluation on the query, you are forcing the server to evaluate for this order by clause much earlier and compute all of the results (including their order) before any can be shown. You’ll likely end up with an entirely different execution plan, and may even void an index (or match of up with a less-desirable index). Without a “TOP (n)” clause, the server can begin showing results as soon as it knows a record will be used.