2012-09-05 70 views
-1

可能重复:
LINQ to Entities does not recognize the methodEF IQueryable的扩展方法选择不工作

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

氏s的作品不错:

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

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

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. 

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

+0

有literaly [上千](http://stackoverflow.com/search?q=LINQ+to+Entities+does+not+recognize + +方法+)与此错误消息的问题。 –

+0

我想你不会仔细阅读这个问题。 此错误消息出于各种原因。 – DeeRain

+0

如果你阅读你发送的内容,你自己就明白了。 – DeeRain

回答

2

正如我在评论说,这是同样的原因每出现此错误消息时:

所使用的EF提供商创建SQL表达式树中包含它没有一个方法理解。
就你而言,这是Active扩展方法。它是表达式树的一部分,因为它在另一个表达式(Select)中使用。

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

为了使您的第二个查询工作,使用:

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

感谢您的回答。我为我的不正确评论道歉。 – DeeRain

+0

欢迎您接受并道歉。 –

+1

我知道这个解决方案,但是如果我将使用它,我会得到代码重复(在Active方法和表达式中)。所以我正在寻找避免重复的方法。 – DeeRain