【问题标题】:SkipWhile fails with "LINQ to Entities does not recognize the method ..."SkipWhile 失败并显示“LINQ to Entities 无法识别方法...”
【发布时间】:2010-12-10 18:50:17
【问题描述】:

我找不到发生以下异常的原因。非常感谢任何帮助。

// EdcsEntities is derived from System.Data.Objects.ObjectContext
EdcsEntities db = new EdcsEntities();

var query = from i in db.Colleges
            select i;

query = query.SkipWhile<College>(x => x.CollegeID != 100);

List<College> l = query.ToList<College>();

例外:

LINQ to Entities 无法识别该方法 'System.Linq.IQueryable1[EDCS.ServiceLayer.DataAccess.College] SkipWhile[College](System.Linq.IQueryable1[EDCS.ServiceLayer.DataAccess.College], System.Linq.Expressions.Expression1[System.Func2[EDCS.ServiceLayer.DataAccess.College, System.Boolean]])' 方法,并且该方法不能翻译成商店表达式。

【问题讨论】:

  • 您可能想要Where 而不是SkipWhile
  • 我想忽略源中的元素,只要条件为真,然后返回剩下的元素。
  • 您可能会发现this question 很有用。它适用于 LINQ to SQL,但它应该同样适用于 LINQ to Entities。

标签: linq-to-entities


【解决方案1】:

您不能将SkipWhile 与 EF 一起使用,因为没有将它们转换为 SQL 的好方法。由于 SQL 查询返回无序集(除非您使用 ORDER BY),因此使用这样的谓词没有意义,因此它们不存在。

在 EF 中使用SkipWhile 的方法是在调用之前将查询转换为带有AsEnumerable() 的对象:

query = query.AsEnumerable().SkipWhile(x => x.CollegeID != 100);

当然你可能想做这样的事情:

query = query.OrderBy(x => x.CollegeId).Where(x => x.CollegeID > 100);

【讨论】:

  • 在这种情况下WhereSkipWhile 有完全不同的行为:Where 返回所有带有CollegeId != 100 的元素,SkipWile 忽略源中的元素,只要CollegeId != 100然后在找到CollegeId == 100 后立即返回剩余的元素。即使在上面的示例中,两种方法具有相同的结果,在这种情况下使用其中一种方法也会产生很大的不同:query = query.OrderBy(x =&gt; x.Name).Where(x =&gt; x.CollegeID &gt; 100); 而不是query = query.OrderBy(x =&gt; x.Name).SkipWhile(x =&gt; x.CollegeID &gt; 100);
猜你喜欢
  • 1970-01-01
  • 2014-08-09
  • 1970-01-01
  • 2012-04-03
  • 2021-11-06
  • 2012-05-03
相关资源
最近更新 更多