在DbSet< TEntity>上迭代与IQueryable< out T> [英] iterating over DbSet<TEntity> vs IQueryable<out T>

查看:61
本文介绍了在DbSet< TEntity>上迭代与IQueryable< out T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用实体框架,我从表中选择一些数据,并使用 foreach 循环对其进行迭代。我想知道下面的示例何时查询数据?

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 examples?

示例1。

var countries = db.WorldCountries;
foreach(var item in countries)
{
    Console.WriteLine("Country: {0}", item.Country);
}

示例2。

var countries = db.WorldCountries.Where(t => t.Country == "Country Name");
foreach(var item in countries)
{
    Console.WriteLine("Country: {0}", item.Country);
}

在第一个示例中,国家/地区 DbSet< WorldCountries> 在第二个示例中,国家/地区 IQueryable< out WorldCountries>

In the first example, countries is DbSet<WorldCountries> In the second example, countries is IQueryable<out WorldCountries>.

在上述示例中没有 .ToList()检索到的数据?是在 foreach 循环开始时是否检索到整个数据集(就像在开始时调用 .ToList()一样)第一次迭代)或查询在循环的每次迭代中发布到数据库。

Without the .ToList() in the above examples how is the data retrieved? Is the entire data set retrieved when the foreach loop starts (as if .ToList() were called at the beginning of the first iteration) or queries are issued to the database on each iteration of the loop.

谢谢。

推荐答案

在两个示例中, IQueryable< WorldCountries> 编译为SQL,并在您输入 foreach 时(在 foreach 调用 GetEnumerator )。因此,您是在第一次迭代之前从db接收结果的,而不是在每个单个迭代中都是逐段的(结果是通过DataReader来的,因此实际数据传输可以针对每个迭代逐段进行,但是我的意思是,那里不是在每次迭代中都是单独的SQL查询。)

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).

请注意, DbSet< T> 也会实现 IQueryable< WorldCountries> ,因此您的两个示例都一样工作,除了第二个示例恰好包含where子句。

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.

何时您添加 .ToList ,它会在返回之前进行迭代并填充列表,因此在这种情况下,您需要从数据库传输所有必需的数据,然后再继续执行下一条语句。

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.

这篇关于在DbSet&lt; TEntity&gt;上迭代与IQueryable&lt; out T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆