为什么LINQ到的entites承认我的自定义方法? [英] Why does LINQ-to-Entites recognize my custom method?
问题描述
本作品:
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键<工作单,布尔>>)
的区别
这新的编辑似乎是正确的澄清:看来 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屋!