Reputation: 53
I was trying to select some columns from a view with the direct way like the below code snippet
var q = new TDSViewConnection();
var trials = q.progressive_filtering_lookup_decoded_v
.Where(z => z.source == "")
.Select(z => z.trial_id);
The SQL statement generated for the above expression is like as below
SELECT
[Extent1].[trial_id] AS [trial_id]
FROM
(SELECT
[progressive_filtering_lookup_decoded_v].[master_protocol_id] AS [master_protocol_id],
[progressive_filtering_lookup_decoded_v].[trial_id] AS [trial_id],
[progressive_filtering_lookup_decoded_v].[source] AS [source],
[progressive_filtering_lookup_decoded_v].[discipline_code] AS [discipline_code],
[progressive_filtering_lookup_decoded_v].[crop_team_code] AS [crop_team_code],
[progressive_filtering_lookup_decoded_v].[crop_name] AS [crop_name],
[progressive_filtering_lookup_decoded_v].[pest_name] AS [pest_name],
[progressive_filtering_lookup_decoded_v].[country_code] AS [country_code],
[progressive_filtering_lookup_decoded_v].[year] AS [year]
FROM
[dbo].[progressive_filtering_lookup_decoded_v] AS [progressive_filtering_lookup_decoded_v]) AS [Extent1]
WHERE
N'' = [Extent1].[source]
The question is why are there two select statements? I think it should be only one statement.
Upvotes: 0
Views: 2937
Reputation: 63136
As the other user posted, your resultant query is a projection result, or a subset of the full query. As such, the query engine will treat the full object as the source, and will simply select the items that you want from it, thus resulting in the sub-query.
If you look at the query plan performance within SQL Server, there is typically no real difference between running the query the way that EF does the query and the way that you might expect to see it.
The key benefit here is that since you only want the one column, EF makes sure that is all that is returned from the database. Typically I find that ensuring you have the smallest result set is the desired function. This becomes even more apparent with more complex projections.
Upvotes: 1
Reputation: 30
With Entity Framework, you will get a SQL generation under the covers of what your LINQ statement expresses. It appears to me that your LINQ statement is performing it's first select based on the preliminary portion of your code, and then when you once again use the '.Select' keyword, you are essentially performing a sub-query on the result set that you previously retrieved.
In other words: var trials = q.progressive_filtering_lookup_decoded_v.Where(z => z.source == "")
Is the initial query, which will return a result set.
Then you are running .Select(z => z.trial_id);
which runs a separate query using your first result set as a starting point.
This is why you are seeing two select statements in your generated SQL.
Upvotes: 0