有一种方法可以强制实体框架在我枚举时一次从Db中读取一条记录吗? [英] Is there a way to enforce Entity Framework to read one record from Db at a time while I enumerate?

查看:47
本文介绍了有一种方法可以强制实体框架在我枚举时一次从Db中读取一条记录吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以强制实体框架一次从Db读取一条记录?

Is there a way to enforce Entity Framework to read one record from Db at a time?

基本上使它像 SqlDataReader一样工作(我只需要向前阅读,就不会更改任何数据!)

Basically to make it work like a SqlDataReader (I need to read forward only and I won't change the data at all!)

为了简化示例,在下面的循环中,我希望EF每次迭代都获得1个城市。

To simplify what I ask with an example, in the loop below, I want EF to obtain 1 city on each iteration.

var context = new CityEntities();

var cities = from c in context.Cities
             select c;

foreach (var c in cities) {
    Console.WriteLine(c);   // I want to have only 1 city in the memory at this point
}

为什么:因为我想利用强类型化的优势编写查询,并避免在我的情况下将查询编写为字符串。

Why : because I want to write the query by using the advantage of strong typing and prevent writing the queries as string in my case.

推荐答案

实体框架实际上一次读取一个实体。如果您在IQueryable上有一个foreach循环(即您没有执行评估),则只有在您访问实体时,实体框架才会具体化。这就是为什么在使用延迟加载时需要启用MARS(多个活动结果集)的原因-当您启动嵌套查询时,外部查询仍在进行中。

Entity Framework is actually reading one entity at a time. If you have a foreach loop on IQueryable (i.e. you did not enforce evaluation) the Entity Framework will materialize each entity only when you get to it. This is the reason why you need to have MARS (Multiple Active Result Sets) enabled when using Lazy Loading - the outer query is still in progress when you start a nested query.

编辑

在EF6中,默认策略现在是缓冲以便能够支持连接弹性。但是,如果不使用连接弹性,则可以关闭缓冲。

In EF6 the default strategy is now to buffer to be able to support connection resiliency. However the buffering can be turned off if connection resiliency is not used.

这篇关于有一种方法可以强制实体框架在我枚举时一次从Db中读取一条记录吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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