iterating over DbSet vs IQueryable

后端 未结 1 2009
予麋鹿
予麋鹿 2021-01-05 07:28

Using Entity Framework I select some data from a table and iterate over it with foreach loop. I am wondering when is the data getting queried in the following e

相关标签:
1条回答
  • 2021-01-05 08:26

    In both examples, the IQueryable<WorldCountries> is compiled to SQL and executed at the point you enter foreach (when foreach calls GetEnumerator). So you receive the result from the db just before the first iteration, not piece by piece on every single iteration.(The results come via a DataReader so actual data transfer may be done piece by piece for each iteration but what I mean is, there is not a separate SQL query on each iteration).

    Note that DbSet<T> also implements IQueryable<WorldCountries>, so your both examples work the same, except the second one happens to include a where clause.

    When you add .ToList, that iterates through and fills up a list before returning, so in that case you transfer all the necessary data from the db before moving on to the next statement.

    0 讨论(0)
提交回复
热议问题