Ultimately it seems like you want to combine expressions. Here's the problem though: Expression trees are immutable, and they will maintain their parameter references which makes it hard to chain these together. However, that's not to say it can't be done (or isn't too difficult). You need the help of an ExpressionVisitor however, that will swap the parent and child parameter references.
class SwapVisitor : ExpressionVisitor
{
private readonly Expression from, to;
public SwapVisitor(Expression from, Expression to)
{
this.from = from;
this.to = to;
}
public override Expression Visit(Expression node)
{
return node == from ? to : base.Visit(node);
}
}
Then you can just chain them together in your GetChildIDExpr
:
Expression<Func<Parent, long>> GetChildIDExpr(Expression<Func<Child, long>> objectIdExpr)
{
Expression<Func<Parent, Child>> parentEX = p => p.Child;
var swap = new SwapVisitor(objectIdExpr.Parameters[0], parentEX.Body);
var newExpr = Expression.Lambda<Func<Parent, long>>(
swap.Visit(objectIdExpr.Body), parentEX.Parameters);
return newExpr;
}
Give that a try and let us know.