'IN'& Linq查询中的“NOT IN”

时间:2010-11-29 05:13:13

标签: c# linq entity-framework entity-framework-4 linq-to-entities

我在LINQPad中测试了以下查询,它运行正常,但VS2010不喜欢它。

var topJobs = from j in streetlightDBEntities.Job
    let mjobid = from m in streetlightDBEntities.Job.Include("Streetlight")
                 where m.Streetlight.StreetlightId == j.Streetlight.StreetlightId
                 orderby m.DateCompleted descending
                 select m.JobId
        where mjobid.Take(5).Contains(j.JobId)
        select j.JobId;

var notTopJobs = streetlightDBEntities.Job.Where(c => !topJobs.Contains(c.JobId));

我收到以下错误:

  

LINQ to Entities无法识别方法'Boolean Contains [String](System.Linq.IQueryable`1 [System.String],System.String)'方法,并且此方法无法转换为商店表达式。< / p>

1 个答案:

答案 0 :(得分:8)

使用Queryable.Any<TSource>

而不是:

var notTopJobs = streetlightDBEntities
      .Job
      .Where(c => !topJobs.Contains(c.JobId));

这样做:

var notTopJobs = streetlightDBEntities
      .Job
      .Where(c => !topJobs.Any(x => x.JobId == c.JobId))

对原始查询执行相同操作。