【问题标题】:Linq Intersect(...).Any() inside of a Where clause throws NotSupportedException在 Where 子句中的 Linq Intersect(...).Any() 抛出 NotSupportedException
【发布时间】:2009-05-05 02:13:52
【问题描述】:

只要 tags 参数不为空,我就会收到 NotSupportedException: 本地序列不能在查询运算符的 LINQ to SQL 实现中使用,除了 包含()运算符。

[WebMethod]
public static object GetAnswersForSurvey(string surveyName, int? surveyYear, IEnumerable<string> tags, IEnumerable<string> benchmarks)
{
    IQueryable<DAL.Answer> results = new DataClassesDataContext().Answers
                                            .OrderBy(a => a.Question.Variable);

    if (!String.IsNullOrEmpty(surveyName)) results = results.Where(a => a.Survey.Name == surveyName);
    if (surveyYear.HasValue) results = results.Where(a => a.Survey.Year == surveyYear.Value);
    if (tags.Any()) results = results.Where(answer => answer.Question.Tags.Select(t => t.Label).Intersect(tags).Any());
    if (benchmarks.Any()) results = results.Where(answer => benchmarks.Contains(answer.Question.BenchmarkCode));

    return results.Select(a => new {
        a.Question.Wording,
        a.Demographic,
        Benchmark = a.Question.BenchmarkCode,
        a.Question.Scale,
        a.Mean,
        a.MEPMean,
        a.NSSEMean
    });
}

我知道按照我尝试的方式可能无法做到这一点。如果不可能,谁能提供任何替代方案?

【问题讨论】:

    标签: c# linq-to-sql asp.net-ajax


    【解决方案1】:

    许多通用 Linq to Object 方法在 Linq to SQL 中不受支持。

    http://msdn.microsoft.com/en-us/library/bb399342.aspx

    另一种方法可能是针对 sql 完成几个子查询,然后将交集操作作为 Linq to Objects 执行

    【讨论】:

    • if (tags.Any()) results = results.AsEnumerable().Where(answer => answer.Question.Tags.Select(t => t.Label).Intersect(tags)。 Any()).AsQueryable();这行得通……但让我觉得很脏。
    【解决方案2】:

    我认为原因是 System.Data.Linq.Table.Intersect 的实现返回了一个 IEnumerable,而它又没有实现 Any() 的无参数版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多