When invoking a method-provided expression on a member property, LinqKit throws an InvalidCastException.

c# entity-framework expression-trees linq linqkit


given a straightforward parent-child class hierarchy I want to apply a child lambda expression to the parent using Linqkit. I also want a utility mechanism to provide the Lambda expression.

public class Foo
    public Bar Bar { get; set; }

public class Bar
    public string Value { get; set; }
    public static Expression<Func<Bar, bool>> GetLambdaX()
        return c => c.Value == "A";

Expression<Func<Foo, bool>> lx = c => Bar.GetLambdaX().Invoke(c.Bar);

The code above fails.

System.InvalidCastException: Unable to cast object of type 
'System.Linq.Expressions.MethodCallExpression' to type 
at LinqKit.ExpressionExpander.VisitMethodCall(MethodCallExpression m)
at LinqKit.ExpressionVisitor.Visit(Expression exp)
at LinqKit.ExpressionVisitor.VisitLambda(LambdaExpression lambda)
at LinqKit.ExpressionVisitor.Visit(Expression exp)
at LinqKit.Extensions.Expand<TDelegate>(Expression`1 expr)
2/2/2015 9:08:17 PM

Accepted Answer

var lambdaX = Bar.GetLambdaX();

Expression<Func<Foo, bool>> lx = c => lambdaX.Invoke(c.Bar);

That works.

Take cautious while writing.

Expression<Func<Foo, bool>> lx = ...

The compiler analyzes this line before to assignment and, in your case, generates a method call expression (i.e. for invoking Bar). GetLambdaX()), which has lx as its parameter.

If you use var..., Bar.GetLambdaX(); will be invoked and assigned, and its result (a lambda expression) will subsequently be utilized in lx = if you use it later.

2/22/2011 12:06:59 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow