When are queries executed on DbContext When are queries executed on DbContext asp.net asp.net

When are queries executed on DbContext


No. The query happens once you enumerate a table. Even in your second example, it still does not connect to the database.

It will connect when you enumerate, for example:

dbContext.Cars.ToList();

Or

foreach (Car c in dbContext.Cars)

Or bind the table to a UI control.

However when you make a where, order by, then by, join etc.. e.g.

var result = dbContext.Cars.Where(c => c.Id == 35).OrderBy(c => c.Name);

You will not connect to the database. You are only preparing the logical sequence of operations to translate into an SQL query.


AFTER THE QUESTION UPDATE

Now, your second example, with the ToList(), enumerate the results and connects to the database to get the data.