为什么LINQ-to-Entites会识别我的自定义方法?

Blu*_*eft 9 c# linq-to-entities entity-framework

这有效:

Entities.WorkOrderSet.Where(MyCustomMethod);
Run Code Online (Sandbox Code Playgroud)

这不是:

Entities.WorkOrderSet.Where(o => MyCustomMethod(o));
Run Code Online (Sandbox Code Playgroud)

([编辑]即使没有new,它也不起作用)

我理解为什么第二个不起作用 - 但为什么世界上第一个工作!? 我不应该在运行时获得"LINQ-to-Entities无法识别方法...",就像第二个一样?

作为参考,这是MyCustomMethod

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

使用EF1,而不是EF4

Nix*_*Nix 6

首先是因为它是一个扩展方法,并且正在将查询作为func执行,然后过滤列表,请参见此处.所以一般来说它会自动转换到哪里

 Where(Func<WorkOrder, bool>
Run Code Online (Sandbox Code Playgroud)

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

Where( Expresion<Func<WorkOrder, bool>>)
Run Code Online (Sandbox Code Playgroud)

这是一篇很好的文章,解释了Expressions vs Func

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

[编辑(BlueRaja)]

这个新的编辑似乎是正确的.澄清:它似乎Func<WorkOrder, bool>是隐含的可投射的Expression<Func<WorkOrder, bool>>,但不是相反的.

Where两种类型都有重载..Where(MyCustomMethod)正在呼唤那个Func<WorkOrder, bool>,而.Where(o => MyCustomMethod(o))正在呼唤那个Expression<Func<WorkOrder, bool>>.