c# – Linq查询中的’IN’和’NOT IN’

前端之家收集整理的这篇文章主要介绍了c# – Linq查询中的’IN’和’NOT IN’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在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 does not recognize the method ‘Boolean Contains[String](System.Linq.IQueryable`1[System.String],System.String)’ method,and this method cannot be translated into a store expression.

解决方法

使用 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))

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

猜你在找的C#相关文章