查询的结果不能被枚举多次 [英] The result of a query cannot be enumerated more than once

查看:36
本文介绍了查询的结果不能被枚举多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架 (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 数组,用于填充 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();
}

当我调试我的代码时,我可以进入 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 但未在用户代码中处理

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);
}

函数 import Search 调用存储的 precedure 返回 SearchItem 的集合.

The function import Search calls a stored precedure to return a collection of SearchItem.

我有一种感觉,由于 ef 的某些原因,foreach 循环无法迭代.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆