Does LINQ-to-SQL support compound queries?

Speaking as a non-C # programmer, I'm curious about the semantics of evaluating LINQ queries, for example:

var people = from p in Person
             where p.age < 18
             select p

var otherPeople = from p in people
                  where p.firstName equals "Daniel"
                  select p

Assuming what Personis an ADO object that defines fields ageand firstNamewhat would it do from a database perspective? In particular, will the query be executed peopleto create a structure in memory, which will then be queried using the query otherPeople? Or will the build otherPeoplejust pull the query data from people, and then create a new query with the databases? So, if I repeated both of these queries, how many SQL statements would be executed?

+5
source share
5 answers

They are composite. This is possible because LINQ queries are actually expressions (code as data) that LINQ providers, such as LINQ-to-SQL, can evaluate and generate the appropriate SQL.

Since LINQ queries are lazily evaluated (for example, they will not be executed until you go to the elements), the code you showed will not actually touch the database. Until you move on to other people or people, SQL will be generated and executed.

+12
source

Yes, the resulting query is compiled. It includes the full where clause. Turn on SQL profiling and see for yourself.

Linq . linq ; . linq , . .

+3
var people = from p in Person
             where p.age < 18
             select p

:

SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName]
FROM [dbo].[Person] AS [t0]
WHERE [t0].[Age] < @p0

@p0 18

var otherPeople = from p in people
                  where p.firstName equals "Daniel"
                  select p

:

SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName]
FROM [dbo].[Person] AS [t0]
WHERE [t0].[FirstName] = @p0

@p0 ""

var morePeople = from p1 in people
                 from p2 in otherPeople
                 where p1.PersonId == p2.PersonId
                 select p1;

:

SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName]
FROM [dbo].[Person] AS [t0], [dbo].[Person] AS [t1]
WHERE ([t0].[PersonId] = [t1].[PersonId]) AND ([t0].[Age] < @p0) AND ([t1].[FirstName] = @p1)

@p0 18, @p1 - "Daniel"

, ToString() IQueryable TextWriter DataContext Log.

+3

people otherPeople IQueryable<Person>.

, , . otherPeople, where.

.ToList() people List<Person> , LINQ-to-Objects SQL.

This behavior is called deferred execution. This means that the request is not executed until it is needed. Before execution, they are simply expression trees that are processed to formulate the final request.

+1
source

Both of these queries will be executed when you try to access the final results. You can try to look at the source SQL created from the properties of the DataContext object.

0
source

All Articles