简体   繁体   English

查询结果不能被多次枚举

[英]The query results cannot be enumerated more than once

Consider the following methods. 请考虑以下方法。 I am getting exception as asked , while repeater binding. 中继器绑定时,我正在按要求获取异常。

Bindrepeater: Bindrepeater:

private void BindRepeater()
{
    var idx = ListingPager.CurrentIndex;
    int itemCount;
    var keyword = Keywords.Text.Trim();
    var location = Area.Text.Trim();
    var list = _listing.GetBusinessListings(location, keyword, idx, out itemCount);
    ListingPager.ItemCount = itemCount;
    BusinessListingsRepeater.DataSource = list.ToList(); // exception here
    BusinessListingsRepeater.DataBind();
}

GetBusinessListings: GetBusinessListings:

public IEnumerable<Listing> GetBusinessListings(string location, string keyword, int index, out int itemcount)
{
    var skip = GetItemsToSkip(index);
    var result = CompiledQueries.GetActiveListings(Context);
    if (!string.IsNullOrEmpty(location))
    {
      result= result.Where(c => c.Address.Contains(location));
    }
    if (!string.IsNullOrEmpty(keyword))
    {
        result = result.Where(c => c.RelatedKeywords.Contains(keyword) || c.Description.Contains(keyword));
    }
    var list = result;

    itemcount = list.Count();
    return result.Skip(skip).Take(10);

}

GetActiveListings : GetActiveListings:

/// <summary>
///   Returns user specific listing
/// </summary>
public static readonly Func<DataContext, IQueryable<Listing>> GetActiveListings =
    CompiledQuery.Compile((DataContext db)
                          => from l in db.GetTable<Listing>()
                             where l.IsActive 
                             select l);

When you assign itemcount you are executing the query the first time. 当您分配itemcount您是第一次执行查询。 Why do you need this? 你为什么需要这个? My suggestion would be not to retrieve the item count there and just 我的建议是不要在那取回物品计数

return result.Skip(skip).Take(10).ToList();

Basically you can't have both, fetch only the results you need and retrieve the total count in one query. 基本上,您不能同时拥有两者,只能获取所需的结果并在一个查询中检索总数。 You could use two seperate querys though. 您可以使用两个单独的查询。

You may want to persist your results as a collection, not an IQueryable . 您可能希望将结果持久化为一个集合,而不是IQueryable

var list = result.ToArray();

itemcount = list.Length;
return list.Skip(skip).Take(10);

The above code may not be correct for paging. 上面的代码对于分页可能不正确。 You likely will have to run the query twice. 您可能必须运行两次查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM