I’m having some trouble understanding the differences between how Expressions and Funcs work.
This problem turned up when someone changed a method signature from:
public static List<Thing> ThingList(Func<Thing, bool> aWhere)
To
public static List<Thing> ThingList(Expression<Func<Thing, bool>> aWhere)
Which broke my calling code. The old calling code (which worked) looked like this:
...
object y = new object();
Func<Thing, bool> whereFunc = (p) => p == y;
things = ThingManager.ThingList(whereFunc);
The new code (which doesn’t work) looks like this:
...
object x = new object();
Expression<Func<Thing, bool>> whereExpr = (p) => p == x;
things = ThingManager.ThingList(whereExpr);
This fails inside ThingList(…) on the line utilizing the expression:
var query = (from t in context.Things.Where(aWhere)
...
With the runtime error:
Unable to create a constant value of type 'System.Object'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
This example is contrived, but my guess is it has something to do with the local object variable x not being properly “copied” into the expression.
Can someone explain how to handle this situation in general, and why the Func works but the Expression doesn’t?
The reason for the change almost certainly was to “push” the evaluation of your predicate into the underlying store, which backs your
context. Instead of bringing allThingsinto memory and then usingFunc<Thing,bool>to decide which ones to keep, the author of the changed API decided to useIQueryable, and needed anExpression<Func<Thing,bool>>for that.You are correct on the origin of the error: unlike in-memory predicates,
IQueryablecannot use objects that it does not know, e.g. arbitrary instances ofobject.What you need to do is to change the expression to avoid referencing objects of data types not supported by your target data store (I assume the expression eventually makes its way into either an Entity Framework or a Linq2Sql context). For example, instead of saying
you should say
(your backing store almost certainly understands integers)