EF IQueryable extension method not working in Select [duplicate]

a 夏天 提交于 2019-12-13 08:29:43

问题


Possible Duplicate:
LINQ to Entities does not recognize the method

I use Entity Framework 4.3

I write extension method:

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

This works good:

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

But i need use this extension method in Select. Look simplified query:

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

(Children - collection of child categories) When query execution I get a error message:

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.

Why does not work? How to write correctly?


回答1:


As stated in my comments, it is the very same reason every time this error message appears:

The expression tree that is used by the EF provider to create the SQL contains a method it doesn't understand.
In your case, this is the Active extension method. It is part of the expression tree as it is used inside another expression (Select).

In your first query, your method is NOT part of the expression tree. Instead it simply changes the expression tree by adding the Where expression to it. That is a fundamental difference.

To make your second query work, use this:

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


来源:https://stackoverflow.com/questions/12278112/ef-iqueryable-extension-method-not-working-in-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!