LINQ to SQL和Contains关键字中的堆栈溢出

ias*_*ons 5 linq contains linq-to-sql

我有一个Extension方法,它应该根据Ids的集合过滤一个Queryable对象(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;
    }
Run Code Online (Sandbox Code Playgroud)

如果从数组或列表创建ID并将其作为可查询列表传入,则它无法正常工作

例如...

 GetNewsItemSummary().WithID(ids.AsQueryable<Guid>())
Run Code Online (Sandbox Code Playgroud)

如果Ids是由LinqToSql请求组成的,它就可以工作了!

这是已知问题:http: //connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?反馈ID = 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;
    }
Run Code Online (Sandbox Code Playgroud)

我现在得到以下异常:

Method 'Boolean Contains(System.Guid)' has no supported translation to SQL.
Run Code Online (Sandbox Code Playgroud)

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

Amy*_*y B 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;
    }
)
Run Code Online (Sandbox Code Playgroud)

针对本地集合的Contains方法的翻译是为.net 3.5开发linq to sql时添加的最后一个特性之一,所以在某些情况下你会期望没有的工作 - 比如翻译IList<T>.

此外,请注意,虽然LinqToSql将愉快地翻译包含大量项目的列表(我已经看到它超过50,000个元素),但SQL Server将只接受单个查询的2,100个参数.

  • 虽然问题和答案都不完全像我的问题,但他们帮助我找出解决方案,即将我的`IList <>`改为`List <>`.瘸子... (2认同)