我在理解表达式和函数的工作方式之间的差异时遇到了一些困难。 这个问题打开了,当有人从改变方法签名:关于传递表达式与函数参数的困惑
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
没有?
是,它使得它的方式到实体框架。我想我必须做两个方法,一个用于Expression,另一个用于Func在必要时使用。 – Erix 2012-01-04 14:32:08