Linq latter processing behavior
-
09-09-2020 - |
Question
In this situation:
var allCustomers = from c in customers select c;
var oldCustomers = from o in allCustomers where o.age > 70 select o;
Will where clause reach database?
Solution
I think you mean:
var oldCustomers = from o in allCustomers where o.age > 70 select o;
And Yes, it will reach the database.
Try using LINQPad to see the SQL code generated. Here's an example:
I have a Actor
table that has the fields:
Id | Name | Age
The code:
var x = from c in Actors where c.Name.Contains("a") select c;
var y = from c in x where c.Age > 0 select c;
gets translated to:
-- Region Parameters
DECLARE @p0 Int = 0
DECLARE @p1 NVarChar(3) = '%a%'
-- EndRegion
SELECT [t0].[Id], [t0].[Name], [t0].[Age]
FROM [Actor] AS [t0]
WHERE ([t0].[Age] > @p0) AND ([t0].[Name] LIKE @p1)
so you can see how it mixes the two queries in only one.
Remember, IEnumerables are lazy, so you unless their elements have to be known (because you iterate through them, or because you do .Count()
to see how many items are, etc), it won't perform any query/operation.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow