Halcyon Halcyon - 2 months ago 25
ASP.NET (C#) Question

The result of a query cannot be enumerated more than once

I am using the entity framework (ef) and am getting the following error:

"The result of a query cannot be enumerated more than once.".

I have a repository class which contains the ef data context. I then have a controller class (not to be confused with MVC controllers) which contains an instance of the repository. So far so good... I have a search method on the controller which is supposed to return an array of
, which is used to populate a Telerik RadComboBox control.

public RadComboBoxItemData[] Search(int id, string searchText)
var query = context.Search(id, searchText);
List<RadComboBoxItemData> result = new List<RadComboBoxItemData>();
foreach (var item in query)
RadComboBoxItemData itemData = new RadComboBoxItemData();
itemData.Text = ""; // assign some text here..;
itemData.Value = ""; /*assign some value here..*/

return result.ToArray();

When I debug my code, I can get into the foreach loop, but then I get an error saying:

An exception of type
occurred in System.Data.Entity.dll but
was not handled in user code

Additional information: The result of
a query cannot be enumerated more than

My entity uses a function import of an existing stored proc.

// EF repository method calling the function imported method on the data context.
public IEnumerable<SearchItem> Search(int id, string searchText)
return this.entityContext.Search(id, searchText);

The function import
calls a stored precedure to return a collection of

I have a feeling that the foreach loop can't iterate because of something with the ef.


Try explicitly enumerating the results by calling ToList().


foreach (var item in query)


foreach (var item in query.ToList())