【发布时间】:2012-01-04 14:20:42
【问题描述】:
我在理解表达式和函数的工作方式之间的差异时遇到了一些麻烦。 当有人从以下位置更改方法签名时出现此问题:
public static List<Thing> ThingList(Func<Thing, bool> aWhere)
到
public static List<Thing> ThingList(Expression<Func<Thing, bool>> aWhere)
这破坏了我的调用代码。旧的调用代码(有效)如下所示:
...
object y = new object();
Func<Thing, bool> whereFunc = (p) => p == y;
things = ThingManager.ThingList(whereFunc);
新代码(不起作用)如下所示:
...
object x = new object();
Expression<Func<Thing, bool>> whereExpr = (p) => p == x;
things = ThingManager.ThingList(whereExpr);
这在 ThingList(...) 中使用表达式失败:
var query = (from t in context.Things.Where(aWhere)
...
出现运行时错误:
Unable to create a constant value of type 'System.Object'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
这个例子是人为的,但我猜它与局部对象变量 x 没有被正确地“复制”到表达式中有关。
有人能解释一下如何处理这种情况,以及为什么Func 有效而Expression 无效?
【问题讨论】:
标签: c# linq linq-to-entities