为什么LINQ-to-Entites会识别我的自定义方法? [英] Why does LINQ-to-Entites recognize my custom method?

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

问题描述

这样做:

  Entities.WorkOrderSet.Where(MyCustomMethod); 

这不是:

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

即使没有,它不工作)



我明白为什么第二个不起作用 - 但为什么在世界上做第一个工作!?不应该在运行时得到一个LINQ到实体不能识别方法,就像第二个? / p>

为了参考,这里是MyCustomMethod

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

使用EF1,而不是EF4

解决方案

首先作品是因为是一种扩展方法,正在将查询作为func执行,然后过滤列表参见这里
所以一般来说,它将自动转换到

  Where(Func< WorkOrder,bool> 

第二个不是因为它将你的where语句推送到db当lambda表达式被评估时,它被展开像这样:

 其中(Expresion< Func< WorkOrder,bool>>)

这是一个很好的表达式 vsnofollow noreferrer>文章 Func



这是另一个SO帖子,有助于解释差异





这个新的编辑看起来是正确的。澄清:似乎 Func< WorkOrd呃,bool> 隐含地转换为表达式< Func< WorkOrder,bool>> ,而不是其他方式。

这两种类型都存在 Where 的重载。 。(MyCustomMethod)正在调用 Func< WorkOrder,bool> 一个,而。其中(o => MyCustomMethod(o))正在调用 Expression&FunC< WorkOrder,bool>>

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-to-Entites会识别我的自定义方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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