NpGsql EntityFramework 6 - "An operation is already in progress" NpGsql EntityFramework 6 - "An operation is already in progress" postgresql postgresql

NpGsql EntityFramework 6 - "An operation is already in progress"


I have succeeded to solve the problem using a ToList<T> right after the linq query like this:

using (ElisContext db = new ElisContext()) {    var q = from a in db.aktie select a;    List<aktie> akties = q.ToList<aktie>();    foreach (aktie a in akties) {        Console.WriteLine("aktie: id {0}, name {1}, market name {2}"                 , a.id, a.name, a.marked.name);    }}

Note the q.ToList<T> that does the trick. .Net postpone the execution of the linq statement to the latest moment, which may be part of the problem. I have tried to use q in the foreach with out success.


The issue is caused by the return type of the GetUsers() method. Since it is IEnumerable<User>, LINQ-to-SQL will load the result into memory (row by row) and subsequent Where, OrderBy, Select, Count, etc. calls will be executed in memory. When the Where condition is evaluated, the original result set is still being iterated over, but the relation User.Role needs to be resolved on the DB (that's where the "An operation is already in progess" error message comes from).

If the return type is changed to IQueryable<User>, the query won't be executed until the Count method is called, and furthermore, the whole query will be translated into SQL returning only the count without ever loading any User records into memory.

See also this related question/answer: Returning IEnumerable<T> vs. IQueryable<T>

The answer suggesting to call ToList() on the query, will load the entire result set into memory, which makes your error go away, but depending on the size of the result set, could also be very inefficient.