Build a specific LINQ expression based on another LINQ expression and a value
Asked Answered
V

2

2

If I've got a LINQ expression of the form:

Expression<Func<MyClass, string, bool>> filterExpression = (x, filterVal) => x.DisplayName.Contains(filterVal);

Is there any way I can get to the expression below?

Expression<Func<MyClass, bool>> filter = x => x.DisplayName.Contains("John");

I need to use the second expression in a Linq-to-Entities Where call.

Vinna answered 16/5, 2011 at 2:29 Comment(2)
Can this work? Expression<Func<MyClass, bool>> filter = x => filterExpression.Compile()(x, "John");Usurpation
Linq-to-Entities won't be able to serialise a compiled expression to SQL.Vinna
S
1

You need to write an ExpressionVisitor that replaces the ParameterExpression with a ConstantExpression.

It would look something like

protected override Expression VisitParameter(ParameterExpression node) {
    if (node.Name == "filterVal")
        return Expression.Constant(something);
    return node;
}
Surratt answered 16/5, 2011 at 2:41 Comment(0)
V
1

In case it's useful the way I solved it was:

public class MyVisitor : ExpressionVisitor
{
    protected override Expression VisitParameter(ParameterExpression node)
    {
        Console.WriteLine("Visiting Parameter: " + node.Name);
        if (node.Name == "filterVal")
        {
            return Expression.Constant("John");
        }
        return node;
    }
}

Expression<Func<MyClass, string, bool>> filterExpression = (x, filterVal) => x.DisplayName.Contains(filterVal);
var filterExpBody = (new MyVisitor()).Visit(filterExpression.Body);
Expression<Func<MyClass, bool>> filter = Expression.Lambda<Func<MyClass, bool>>(filterExpBody, filterExpression.Parameters[0]);
Vinna answered 16/5, 2011 at 4:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.