问题
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