How to deal with large result sets with Linq to Entities?

前端 未结 2 1711
时光取名叫无心
时光取名叫无心 2021-02-06 09:54

I have a fairly complex linq to entities query that I display on a website. It uses paging so I never pull down more than 50 records at a time for display.

But I also wa

2条回答
  •  梦谈多话
    2021-02-06 10:31

    Look at the return value of the LINQ query. It should be IEnumerable<>, which only loads one object at a time. If you then use something like .ToList(), they will all be loaded into memory. Just make sure your code doesn't maintain a list or use more than one instance at a time and you will be fine.

    Edit: To add on to what people have said about foreach... If you do something like:

    var query = from o in Objects
                where o.Name = "abc"
                select o;
    
    foreach (Object o in query)
    {
       // Do something with o
    }
    

    The query portion uses deferred execution (see examples), so the objects are not in memory yet. The foreach iterates through the results, but only getting one object at a time. query uses IEnumerator, which has Reset() and MoveNext(). The foreach calls MoveNext() each round until there are no more results.

提交回复
热议问题