dragonfly
dragonfly

Reputation: 17773

Enumerating stored procedure result - The result of a query cannot be enumerated more than once

I'm calling stored procedure:

ObjectResult<ComplexType1> result = context.ListSomething(model.SelectedDatabase);
ViewBag.WebGrid = new WebGrid(source: result, rowsPerPage: int.MaxValue, canSort: false, canPage: false);

however when passing result as a source to WebGrid I receive:

System.InvalidOperationException: The result of a query cannot be enumerated more than once.

I'm a bit supprised as ObjectResult implements IEnumerable (not IQueryable). What is the background behind that exception and why I have to call ToList() method:

var result = context.ListSomething(model.SelectedDatabase).ToList();
ViewBag.WebGrid = new WebGrid(source: result, rowsPerPage: int.MaxValue, canSort: false, canPage: false);

to make it work? Could you perhaps provide me with some documentation that explains it (for instance from Programming Entity Framework, 2nd Edition, as I'm reading it now, but I don't remember anything that would explain that mechanism so far).

Thanks, Pawel

Upvotes: 3

Views: 5741

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364269

It is because ObjectResult<T> internally accesses DataReader which allows enumerating result only once in forward only way so if you want to iterate the result again without calling ToList first you must execute stored procedure again and get new ObjectResult<T> instance.

Upvotes: 5

Related Questions