EF6 IQueryable Deferred Execution and Select
I've recently been building a new EF data access layer for our system at work and have obviously been asked a lot of questions about how it compares to the flexibility of using the existing native ADO.Net framework. One question was - where there are tables with a large number of fields (100s) and we're only interested in a subset of these, does EF pull back all the fields? I was pretty sure if you query a DataSet using Select, the deferred execution on the IQueryable interface would return the minimum data required for the Select projection. These tests prove it (I used SQL Server Profiler to capture the SQL):
For a simple select statement to return the IDs from a table like this:
var ctx = new DemoContext();
var item = ctx.Line.Select(l => l.ID).ToList();
The following SQL is executed
SELECT
[Extent1].[ID] AS [ID]
FROM [dbo].[Line] AS [Extent1]
We can see that only the ID field is returned.
Now another example, where we are projecting the results into an anonymous object:
var item = ctx.Line.Select(l => new { id = l.ID, name = l.Name }).ToList();
And the resultant SQL:
SELECT
1 AS [C1],
[Extent1].[ID] AS [ID],
[Extent1].[Name] AS [Name]
FROM [dbo].[Line] AS [Extent1]
Here we get the fields required for the anonymous object and an extra C1 field which is a dummy PK for the object.