一个查询的结果不能枚举不止一次 [英] The result of a query cannot be enumerated more than once
问题描述
我使用的是实体框架(EF)和我得到以下错误:
I am using the entity framework (ef) and am getting the following error:
的查询的结果不能枚举不止一次。
"The result of a query cannot be enumerated more than once.".
我有一个包含EF的数据上下文的存储库类。然后,我有一个包含库实例的控制器类(不要与MVC控制器混淆)。到目前为止好......我有一个应该返回 RadComboBoxItemData code>的数组,它是用来填充Telerik的radcombobox控件控制控制器上的搜索方法。
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 RadComboBoxItemData
, 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..*/
result.Add(itemData);
}
return result.ToArray();
}
在调试我的code,我可以进入foreach循环,但后来我得到一个错误说:
When I debug my code, I can get into the foreach loop, but then I get an error saying:
类型的例外
System.InvalidOperationException
发生在System.Data.Entity.dll但
在用户code没有处理
An exception of type 'System.InvalidOperationException' 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 once.
我的实体使用现有的存储过程的函数导入。
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);
}
功能导入搜索
调用存储precedure返回 SearchItem
的集合。
The function import Search
calls a stored precedure to return a collection of SearchItem
.
我有一种感觉,foreach循环不能因事与EF迭代。
I have a feeling that the foreach loop can't iterate because of something with the ef.
推荐答案
尝试通过调用明确列举结果了ToList()
。
Try explicitly enumerating the results by calling ToList()
.
修改
foreach (var item in query)
到
foreach (var item in query.ToList())
这篇关于一个查询的结果不能枚举不止一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!