EF IQueryable扩展方法在Select中不起作用 [英] EF IQueryable extension method not working in Select

查看:456
本文介绍了EF IQueryable扩展方法在Select中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

LINQ to Entities不识别方法

我使用实体框架4.3

I use Entity Framework 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中使用这种扩展方法。
查看简化的查询:

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?

推荐答案

正如我的意见所述,这是同样的原因时间出现此错误消息:

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

EF提供程序用于创建SQL的表达式树包含一个它不明白的方法。

在您的情况下,这是 Active 扩展方法。它是表达式树的一部分,因为它在另一个表达式中使用(选择)。

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).

在您的第一个查询,您的方法是表达式树的一部分 NOT 。而是通过向其中添加 Where 表达式简单地更改表达式树。这是一个根本的区别。

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() 

这篇关于EF IQueryable扩展方法在Select中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆