Search code examples
entity-frameworklinqlinq-to-entities

Does calling Select New result in the underlying query being executed?


If you append .ToList() to a query, it results in the query executing against the database. If you use Select New does this immediately execute the query, as well, or does it still allow the query to be changed before execution?


If needed, here is an example:

var query = db.Cars();

if(model.CarNameSearch != "")
   query = query.where(u => u.CarName == model.CarNameSearch);

return query.ToList();

In the above example, the query doesn't actually execute against the database until .ToList() is called.

If instead I do this, does Select New result in the query executing before the return:

var query = from cars in db.Cars
            select New MyResult{
                 MyModelCarName = cars.CarName,
                 MyModelCarColor= cars.Color
            };

if(model.CarNameSearch != "")
   query = query.where(u => u.MyModelCarName == model.CarNameSearch);

return query.ToList();

Solution

  • Using new or not doesn't matter here. It's the LINQ method. The query syntax from - select is Select() under the covers and this is one of the methods with deferred execution.

    So the second code fragment is a perfectly valid way to compose a query expression with deferred execution that will execute no sooner than ToList.