查询的结果不能多​​次枚举。

时间:2017-02-22 18:46:14

标签: c# asp.net .net entity-framework linq

我有一个listview对话框,用于将数据绑定到该列表视图。

private void BindListView(string DCLookupMstr_Value, int reportCatId, string DCLookup_Value = null)

    {          

         using (Model.OperationalAnalyticsEntities oadb = new Model.OperationalAnalyticsEntities())
            {
                var res = oadb.prGetDailyCensusLookup(DCLookupMstr_Value, reportCatId, DCLookup_Value);
                Session["LookupValues"] = res;
                lvLookup.DataSource = res.ToList();
                lvLookup.DataBind();
            }            
    }

我在listview对话框中放了一个搜索框(文本框)。如果用户键入任何text / chars,则使用linq query..populate listview再次使用包含给定chars的值。我的代码在

之下
protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
        var text = txtSearch.Text;
        //var list = new List<Model.prGetDailyCensusLookup_Result>();
        var lookUpValue = Session["LookupValues"] as ObjectResult<Model.prGetDailyCensusLookup_Result>;
        var list = lookUpValue.Where(x => x.DCLookup_Value.Contains(text));

        lvLookup.DataSource = list.ToList();
        lvLookup.DataBind();  
     }

我得到的“查询结果不能多​​次枚举”,我添加了.ToList()。我不确定我错过了什么。

请帮助!

2 个答案:

答案 0 :(得分:1)

BindListView中,当您执行.ToList()时,它会首次枚举查询。而你在会话中存储的是查询本身。当您在.ToList()中再次txtSearch_TextChanged时,它会再次枚举该查询,但不支持该查询。

您应该在会话中存储.ToList()的结果,而不是查询:

Session["LookupValues"] = lvLookup.DataSource = res.ToList();

答案 1 :(得分:0)

您在Session中存储的值是LINQ查询,而不是查询的结果。第二次使用它(list.ToList())时会抛出此错误。

通过将结果作为列表存储在Session中,可以轻松解决此问题。

var res = oadb.prGetDailyCensusLookup(DCLookupMstr_Value, reportCatId, DCLookup_Value)
              .ToList();
Session["LookupValues"] = res;
lvLookup.DataSource = res;
lvLookup.DataBind();