为什么LINQ到的entites承认我的自定义方法? [英] Why does LINQ-to-Entites recognize my custom method?

查看:145
本文介绍了为什么LINQ到的entites承认我的自定义方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本作品:

  Entities.WorkOrderSet.Where(MyCustomMethod); 

这不:

  Entities.WorkOrderSet.Where(O = GT; MyCustomMethod(O)); 

即使没有,它不工作)



我理解为什么第二不起作用 - 但是为什么在世界上做的第一件工作!?我不应该得到的LINQ到实体无​​法识别方法......的在运行时,如与第二<? / p>

有关参考,在这里是MyCustomMethod

 公共BOOL MyCustomMethod(工作单工作单)
{
返回workOrder.WorkOrderNum.StartsWith(A,StringComparison.CurrentCultureIgnoreCase)!;
}

使用EF1,不EF4


解决方案

第一部作品,因为它<罢工>是一个扩展方法,是正在执行的查询作为FUNC,然后过滤你的看到这里。
所以一般来说它会自动施放到哪里

 其中(Func键<工作单,布尔> 

二不,因为它是推你的WHERE语句到数据库。当lambda表达式求值,它被扩展像这样的:

 凡(中表达< Func键<工作单,布尔>>)

下面是一个很好的文章解释表达式 VS Func键



这里是另一个SO后,有助于解释



的区别



这新的编辑似乎是正确的澄清:看来 Func键<工作单,布尔> 隐式强制转换为表达式来。 FUNC<工作单,布尔>> ,而不是周围的其他方法



有是重载其中,<。 / code>这两种类型。 。凡(MyCustomMethod)在调用 Func键<工作单,布尔> 之一,而。其中(O => MyCustomMethod(O))在调用表达式来; Func键<工作单,布尔>> 有一个


This works:

Entities.WorkOrderSet.Where(MyCustomMethod);

This does not:

Entities.WorkOrderSet.Where(o => MyCustomMethod(o));

([Edit] Even without new, it doesn't work)

I understand why the second doesn't work - but why in the world does the first work!? Shouldn't I get a "LINQ-to-Entities does not recognize the method..." at runtime, like with the second?

For reference, here is MyCustomMethod

public bool MyCustomMethod(WorkOrder workOrder)
{
    return !workOrder.WorkOrderNum.StartsWith("A", StringComparison.CurrentCultureIgnoreCase);
}

Using EF1, not EF4

解决方案

First works because it is an extension method and is is executing the query as a func, and then filtering your list see here. So in general it would automatically cast the where to

 Where(Func<WorkOrder, bool>

Second doesn't because it is pushing your where statement down to the db. When the lambda expression is evaluated it is expanded like this:

Where( Expresion<Func<WorkOrder, bool>>)

Here is a good article that explains Expressions vs Func

Here is another SO post that helps to explain the difference

[Edit (BlueRaja)]

This new edit appears to be correct. To clarify: it seems Func<WorkOrder, bool> is implicitly castable to Expression<Func<WorkOrder, bool>>, but not the other way around.

There are overloads of Where for both types. .Where(MyCustomMethod) is calling the Func<WorkOrder, bool> one, whereas .Where(o => MyCustomMethod(o)) is calling the Expression<Func<WorkOrder, bool>> one.

这篇关于为什么LINQ到的entites承认我的自定义方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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