On my project written in C#, I've found a HUGE predicate that is used in this method of linq :
public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate);
this predicate works perfectly, but it as so much condition that I struggled a lot before understanding it. I would like to make it readable. So I wrote several Expression.
But I have a runtime exception like this one : The dreaded "parameter was not bound in the specified LINQ to Entities query expression" exception
I wanted to try the answer but I still don't understand why the parameter (c) is a problem see :
// in a method
Func<string, Expression<Func<TEntity, bool>>> expr1 = (query) => return (c) => ... ;
Func<string, Expression<Func<TEntity, bool>>> expr2 = (query) => return (c) => ... ;
var expr = Expression.AndAlso(expr1("a string").Body, expr2("same string").Body);
return Expression.Lambda<Func<TEntity, bool>>(expr , expr1("a string").Parameters[0]);
My question is to understand why this exception occures as finally I reverted to the huge predicate.
Because where you see a single
c
parameter, in truth there are two differentc
parameters (let's call themc1
andc2
). So when you merge the two expressions you have:And the CLR gets angry because it can't find the
c2
.Worse, as you wrote your code, you have three
c
!This because you rebuild
expr1("a string")
twice (in theExpression.AndAlso(expr1("a string").Body
and in theexpr1("a string").Parameters[0]
)!You should have saved it!
To give a clear example:
Now... My version of parameter replacer:
You can use to change a single parameter or a parameter array... You can use it like: