I am looking for a way to combine two lambda expressions, without using an Expression.Invoke on either expression. I want to essentially build a new expression
Update: the below answer generates an "Invoke" which EF does not support.
I know this is an old thread, but I have the same need and I figured out a cleaner way to do it. Assuming that you can alter your "expression2" to user a generic lambda, you can inject one like this:
class Program
{
private static Expression> GetValueFromFoo(Func getFoo)
{
return t => getFoo(t).Bar.Value;
}
static void Main()
{
Expression> getValueFromBar = GetValueFromFoo(m => m.SubModel.Foo);
// test it worked
var func = getValueFromBar.Compile();
Model test = new Model
{
SubModel = new SubModel
{
Foo = new Foo
{
Bar = new Bar { Value = "abc" }
}
}
};
Console.WriteLine(func(test)); // "abc"
}
}