Deferred Execution means that queries are not executed immediately at the time it's being created. The benefit of this is to improve performance by avoiding unnecessary executions. It also allows the query to be extendable when needed such as sorting, filtering.
In the example below, the queries to retrieve courses are not being executed yet
var context = new DbContext();
var courses = context.Courses
.Where(c => c.Level == 1)
.OrderBy(c => c.Name);
The query is only executed when one of the following scenarios occurs:
- Iterating over query variable
- Calling ToList, ToArray, ToDictionary
- Calling First, Last, Single, Count, Max, Min, Average
For example when we loop through the course or turn the result to a list:
foreach ( var c in courses)
Console.WriteLine(c.Name);
OR
context.Courses
.Where(c => c.Level == 1)
.OrderBy(c => c.Name).ToList();
Comments
Post a Comment