【问题标题】:Stack overflow in LINQ to SQL and the Contains keywordLINQ to SQL 和 Contains 关键字中的堆栈溢出
【发布时间】:2010-11-01 00:09:19
【问题描述】:

我有一个扩展方法,它应该根据一组 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.

所以...我要做的就是根据一个列表或一组 Guid 过滤我的新闻集合...想法???

【问题讨论】:

  • 你知道,“stackoverflow”标签通常用于元问题,而“stack-overflow”标签更适合真正的堆栈溢出。

标签: linq linq-to-sql contains


【解决方案1】:

这将翻译。

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 开发中添加的最后一个功能之一,因此在某些情况下您会期望工作不会 - 例如 @ 的转换987654322@.

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

【讨论】:

  • 虽然问题和答案都不完全像我的问题,但他们帮助我找出了解决方案,即将我的IList&lt;&gt;'s 更改为List&lt;&gt;'s。跛脚的虫子……
猜你喜欢
  • 2023-04-11
  • 1970-01-01
  • 2019-05-18
  • 2015-07-11
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
相关资源
最近更新 更多