Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

linq - Dividing an Expression in C# using Expression.AndAlso() causes an Exception

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because where you see a single c parameter, in truth there are two different c parameters (let's call them c1 and c2). So when you merge the two expressions you have:

c1 => c1.Something && c2.SomethingElse;

And the CLR gets angry because it can't find the c2.

Worse, as you wrote your code, you have three c!

c3 => c1.Something && c2.SomethingElse

This because you rebuild expr1("a string") twice (in the Expression.AndAlso(expr1("a string").Body and in the expr1("a string").Parameters[0])!

You should have saved it!

var temp1 = expr1("a string");
var temp2 = expr2("same string");

var expr = Expression.AndAlso(temp1.Body, temp2.Body);

// now fix the expr so that it uses the parameters of temp1

return Expression.Lambda<Func<TEntity, bool>>(expr, temp1.Parameters);

To give a clear example:

var temp1a = expr1("a string");
var temp1b = expr1("a string");
var temp2 = expr2("same string");

Console.WriteLine(temp1a.Parameters[0] == temp1b.Parameters[0]); // False
Console.WriteLine(temp1a.Parameters[0] == temp2.Parameters[0]); // False

Now... My version of parameter replacer:

public class SimpleParameterReplacer : ExpressionVisitor
{
    public readonly ReadOnlyCollection<ParameterExpression> From;
    public readonly ReadOnlyCollection<ParameterExpression> To;

    public SimpleParameterReplacer(ParameterExpression from, ParameterExpression to)
        : this(new[] { from }, new[] { to })
    {
    }

    public SimpleParameterReplacer(IList<ParameterExpression> from, IList<ParameterExpression> to)
    {
        if (from == null || from.Any(x => x == null))
        {
            throw new ArgumentNullException("from");
        }

        if (to == null || to.Any(x => x == null))
        {
            throw new ArgumentNullException("to");
        }

        if (from.Count != to.Count)
        {
            throw new ArgumentException("to");
        }

        // Note that we should really clone from and to... But we will
        // ignore this!
        From = new ReadOnlyCollection<ParameterExpression>(from);
        To = new ReadOnlyCollection<ParameterExpression>(to);
    }

    protected override Expression VisitParameter(ParameterExpression node)
    {
        int ix = From.IndexOf(node);

        if (ix != -1)
        {
            node = To[ix];
        }

        return base.VisitParameter(node);
    }
}

You can use to change a single parameter or a parameter array... You can use it like:

var temp1 = expr1("a string");
var temp2 = expr2("same string");

var expr = Expression.AndAlso(temp1.Body, temp2.Body);
expr = new SimpleParameterReplacer(temp2.Parameters, temp1.Parameters).Visit(expr);

return Expression.Lambda<Func<TEntity, bool>>(expr, temp1.Parameters);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...