Have you noticed that many statements made with Entity Framework end with a ToList or a FirstOrDefault? The reason why we do this is because Entity Framework works with deferred execution. The idea is that you use a sequence of functions to build a query, however, the query is not executed until you indicate it. There are several ways to tell the Entity Framework that we want to execute a query that we have built, functions like ToList and FirstOrDefault tell Entity Framework that we already want to execute the query.
The idea is that when we use functions like Where, OrderBy and Select, an IQueryable is returned, which allows us to build a query, step by step, until at the end, this query is executed when we indicate it. So, for example, if we want to obtain a list of all the records in a table, sorted by date of birth in descending order and that were born before 1990, and suppose that it is a table of students, then we have the following two ways that are equivalent:
using (var context = new ApplicationDbContext()) { // First Way: Functions in a row var students1 = context.Students .Where(x => x.Birthdate.Year < 1990) .OrderByDescending(x => x.Birthdate).ToList(); // Second Way: Functions in several lines var query = context.Students.AsQueryable(); query = query.Where(x => x.Birthdate.Year < 1990); query = query.OrderByDescending(x => x.Birthdate); var students2 = query.ToList(); }
Why does this matter? Because sections of your query can be dynamic, that is, they can be used or not depending on the value of some variable. Under a certain condition you may or may not use the Where, or the OrderByDescending, or any other function. This gives you more power when generating queries with Entity Framework. For example, in the following code, the order in which we are going to bring the elements depends on the Boolean variable orderByAscending:
using (var context = new ApplicationDbContext()) { var query = context.Students.AsQueryable(); query = query.Where(x => x.Birthdate.Year < 1990); if (orderByAscending){ query = query.OrderBy(x => x.Birthdate); } else{ query = query.OrderByDescending(x => x.Birthdate); } var students2 = query.ToList(); }