1

Having such code

foreach (Order order in dbContext.Orders)
{
    // some operations
}

Are Orders fetched from db after each iteration? Is there any need to call ToList() on dbContext.Orders?

Isma
  • 14,604
  • 5
  • 37
  • 51
kriss
  • 976
  • 17
  • 27
  • 3
    The implementation of `ToList` will likely do exactly this, adding items to a list in the loop body. – spender Nov 09 '18 at 12:39
  • If you are interested in what it submits to the database, you should run a SQL Trace. But @spender is correct. – mjwills Nov 09 '18 at 12:40

1 Answers1

1

It does not load one order per one iteration of the foreach loop. Your code loads the entire query result into memory when enumerated.

No need to List() your IQueryable<Order> type in case you use foreach on them. You query is materilized when you invoke ToList() or when you use foreach loop.

See more info about Query Execution

Dmitry Stepanov
  • 2,776
  • 8
  • 29
  • 45