Query Execution
After a LINQ query is created by a user, it is converted to a command tree. A command tree is a representation of a query that is compatible with Telerik Data Access. The command tree is then executed against the data source. At query execution time, all query expressions (these are all components of the query) are evaluated, including those expressions that are used in result materialization.
At what point query expressions are executed - this can vary. 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. This is described later in this topic.
Deferred Execution
The query variable itself only stores the query commands when the query is designed to return a sequence of values. If the query does not contain a method that will cause immediate execution, the actual execution of the query is deferred until you iterate over the query variable in a foreach loop. The query is executed against the server every time you iterate over the query variable. Deferred execution allows multiple queries to be combined or a query to be extended. When this occurs, the query is modified to include the new operations and the eventual execution will reflect the changes.
Immediate Execution
In contrast to the deferred execution of queries that produce a sequence of values, queries that return a singleton value are executed immediately. Some examples of singleton queries are Average, Count, First, and Max. These are executed immediately because the query must produce a sequence to calculate the singleton result. You can also force immediate execution. This is useful when you want to cache the results of a query. To force the immediate execution of a query that does not produce a singleton value, you can call the ToList method or ToArray method.
Store Execution
Some expressions in the query might be executed on the client. In general, most query execution is expected to occur on the server.
Literals and Parameters
Local variables, such as the customerID variable in the following example, are evaluated on the client.
using ( FluentModel dbContext = new FluentModel() )
{
string customerId = "ALFKI";
Customer c = dbContext.Customers.Where( c => c.CustomerID == customerId ).
FirstOrDefault();
}
Using dbContext As New FluentModel()
Dim customerId As String = "ALFKI"
Dim c As Customer = dbContext.Customers.Where(Function(c) c.CustomerID = customerId).
FirstOrDefault()
End Using