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
  • 13,813
  • 5
  • 37
  • 49
kriss
  • 936
  • 14
  • 26
  • 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,588
  • 6
  • 25
  • 42