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

ⅰ亾dé卋堺 提交于 2019-12-11 06:24:21

问题


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

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

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.


回答1:


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.

EDIT

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.




回答2:


You can try this

while(cities.Any())
{
    var city = cities.First();
    cities = cities.Skip(1);
}

But you may end up with very unoptimal SQL. So I highly recommend you loading all records at once.



来源:https://stackoverflow.com/questions/12918294/is-there-a-way-to-enforce-entity-framework-to-read-one-record-from-db-at-a-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!