Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through IQueryable with foreach results in an out of memory exception

I'm iterating through a smallish (~10GB) table with a foreach / IQueryable and LINQ-to-SQL. Looks something like this:

using (var conn = new DbEntities() { CommandTimeout = 600*100})
{
     var dtable = conn.DailyResults.Where(dr => dr.DailyTransactionTypeID == 1);
     foreach (var dailyResult in dtable)
     {
        //Math here, results stored in-memory, but this table is very small. 
        //At the very least compared to stuff I already have in memory. :)
     }
}

The Visual Studio debugger throws an out-of memory exception after a short while at the base of the foreach loop. I'm assuming that the rows of dtable are not being flushed. What to do?

like image 872
Gleno Avatar asked Sep 10 '10 20:09

Gleno


People also ask

Can you foreach an IQueryable?

If you use IQueryable with foreach then query will be evaluated and executed at the same time. Some of the important points about IQueryable<T> are as follows: It implements IEnumerable <T> so the results can be iterated using foreach. It is best suited to query against external data sources.

What is IQueryable return?

IQueryable is executed. // // Returns: // A System.Type that represents the type of the element(s) that are returned when. // the expression tree associated with this object is executed.

What is IQueryable in Linq?

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of "executing an expression tree" is specific to a query provider.


1 Answers

The IQueryable<DailyResult> dtable will attempt to load the entire query result into memory when enumerated... before any iterations of the foreach loop. It does not load one row during the iteration of the foreach loop. If you want that behavior, use DataReader.

like image 78
Amy B Avatar answered Sep 18 '22 13:09

Amy B