5

我有一个扩展方法,它应该根据 Id 的集合过滤一个可查询的对象(IQueryable)......

请注意,IQueryable 是通过 LinqToSql 请求从我的数据库中获取的

 public static IQueryable<NewsItemSummary> WithID(this IQueryable<NewsItemSummary> qry, IQueryable<Guid> Ids)
    {
        return from newsItemSummary in qry
               where Ids.Contains(newsItemSummary.ID)
               select newsItemSummary;
    }

如果Ids是从数组或列表创建并作为可查询列表传入,则它不起作用

例如...

 GetNewsItemSummary().WithID(ids.AsQueryable<Guid>())

如果Ids是由 LinqToSql 请求组成的,它确实有效!

这是已知问题: http ://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=355026

我的 Ids 集合不能来自 LinqToSql 请求...

请注意,如果我更改函数以使其使用 IList 而不是 IQueryable....

 public static IQueryable<NewsItemSummary> WithID(this IQueryable<NewsItemSummary> qry, IList<Guid> Ids)
    {
        return from newsItemSummary in qry
               where Ids.Contains(newsItemSummary.ID)
               select newsItemSummary;
    }

我现在得到以下异常:

Method 'Boolean Contains(System.Guid)' has no supported translation to SQL.

所以......我想做的就是根据列表或Guids数组过滤我的新闻集合......想法???

4

1 回答 1

11

这将翻译。

public static IQueryable<NewsItemSummary> WithID(
    this IQueryable<NewsItemSummary> qry,
    List<Guid> Ids
)
    {
        return from newsItemSummary in qry
               where Ids.Contains(newsItemSummary.ID)
               select newsItemSummary;
    }
)

针对本地集合的 Contains 方法的翻译是 .net 3.5 的 linq to sql 开发中添加的最后一个功能之一,因此在某些情况下您会期望工作不会 - 例如IList<T>.

另外,请注意,虽然 LinqToSql 会愉快地翻译包含大量项目的列表(我已经看到它可以处理超过 50,000 个元素),但 SQL Server 对于单个查询仅接受 2,100 个参数。

于 2009-06-07T14:38:20.807 回答