Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How and When LINQ Queries are Translated and Evaluated?

I have a LINQ to SQL Query as below:

var carIds = from car in _db.Cars
           where car.Color == 'Blue'
           select car.Id;

The above will be translated into the below sql finally:

select Id from Cars 
where Color = 'Blue'

I've read that the phases are:

  1. LINQ to Lambda Expression
  2. Lambda Expression to Expression Trees
  3. Expression Trees to SQL Statements
  4. SQL Statements gets executed

So, my questions are when and how does this get translated and executed?

I know that phase 4 happens at runtime when my "carIds" variable get accessed within a foreach loop.

foreach(var carId in carIds) // here?
{
  Console.Writeline(carId) // or here?
}

What about the other phases? when do they occur? at compile time or runtime? at which line (on the definition or after the definition, when accessed or before it gets accessed)?

like image 935
The Light Avatar asked Jan 04 '13 11:01

The Light


People also ask

How LINQ queries converted into SQL queries?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

When the LINQ query is executed?

LINQ queries are always executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution. You can also force a query to execute immediately, which is useful for caching query results.

How do LINQ queries work?

In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, . NET collections, and any other format for which a LINQ provider is available.

What are the two types of LINQ queries?

LINQ queries can be written in two syntax types, a Query Syntax and a Method Syntax.


1 Answers

What you are talking about is deferred execution - essentially, the linq to SQL query will be executed at the time you attempt to enumerate the results (e.g. iterate round it, .ToArray() it etc).

In your example, the statement is executed on the following line:

foreach(var carId in carIds)

See this MSDN article on LINQ and Deferred Execution

like image 170
AdaTheDev Avatar answered Sep 28 '22 17:09

AdaTheDev