【问题标题】:EF IQueryable extension method not working in Select [duplicate]EF IQueryable 扩展方法在 Select [重复] 中不起作用
【发布时间】:2012-08-29 23:26:19
【问题描述】:

可能重复:
LINQ to Entities does not recognize the method

我使用实体框架 4.3

我写扩展方法:

public static IQueryable<TSource> Active<TSource>(this IQueryable<TSource> source) where TSource : class, IStatusable
{
    return source.Where(s => s.Status == (int)StatusEnum.Enabled);
}

这很好用:

var cat=Context.Categories.Active().ToList()

但我需要在 Select 中使用此扩展方法。 看简化查询:

return Context.Categories
 .Select(c => new { Children=c.Children.AsQueryable().Active()})
 .ToList()

(Children - 子类别的集合) 执行查询时,我收到一条错误消息:

LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[Portal.FrontOffice.Model.Category] Active[Category](System.Linq.IQueryable`1[Portal.FrontOffice.Model.Category])' method, and this method cannot be translated into a store expression.

为什么不工作?如何正确书写?

【问题讨论】:

  • 确实有thousands 的问题与此错误消息有关。
  • 我猜你没有仔细阅读这个问题。出现此错误消息的原因有多种。
  • 如果您阅读了您发送的内容,您自己就明白了。
  • 这个错误信息每次出现的原因都是一样的。
  • 我认为你对这个主题并不精通。

标签: linq entity-framework entity-framework-4 iqueryable


【解决方案1】:

正如我的 cmets 所述,每次出现此错误消息时,原因完全相同

EF 提供程序用来创建 SQL 的表达式树包含一个它不理解的方法。
在您的情况下,这是 Active 扩展方法。它是表达式树的一部分,因为它在另一个表达式 (Select) 中使用。

在您的第一个查询中,您的方法不是表达式树的一部分。相反,它只是通过向其添加Where 表达式来更改表达式树。这是一个根本的区别。

要使您的第二个查询正常工作,请使用:

return Context.Categories 
              .Select(c => new { Children=c.Children
                                           .Where(s => s.Status == 
                                                       (int)StatusEnum.Enabled) }) 
              .ToList() 

【讨论】:

  • 感谢您的回答。对于我的错误评论,我深表歉意。
  • 不客气,接受道歉。
  • 我知道这个解决方案,但如果我使用它,我会得到代码重复(在 Active 方法和表达式中)。所以我正在寻找一种避免重复的方法。
  • 我发现的唯一方法是在任何地方使用表达式(而不是 Active)。或者使用一些查询。
  • @DeeRain:我知道,这首先是扩展方法的原因,不是吗?但是你根本不能在这个查询中使用你的扩展方法。一种可能的解决方案是直接查询包含子项的表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 1970-01-01
相关资源
最近更新 更多