-1

可能重复:
LINQ to Entities 无法识别该方法

我使用实体框架 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()

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

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.

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

4

1 回答 1

2

正如我在评论中所述,每次出现此错误消息时都是相同的原因:

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

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

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

return Context.Categories 
              .Select(c => new { Children=c.Children
                                           .Where(s => s.Status == 
                                                       (int)StatusEnum.Enabled) }) 
              .ToList() 
于 2012-09-05T10:58:40.493 回答