I am dynamically generating Expression trees to be sent off to LINQ to Entities. I am providing a framework and I allow developers to specify output columns as lambda expressions.
For instance, say they have a column they can specify that the way to pull the value from the database is:
p => p.Aliases.Count()
and another column is:
p => p.Names.Where(n => n.StartsWith("hello"))
The problem here is that I need to combine both of these into a single expression.
My first attempt was:
getter = field.SelectorExpression.Body;
And I get the error message The parameter 'p' was not bound in the specified LINQ to Entities query expression
which makes since because LINQ can't know what P is in p.Aliases.Count()
.
The next thing I tried was:
getter = Expression.Invoke(field.OrderBySelector, new[] {parameter});
However, then I recieve the message The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.
Which also makes since because I don't expect SQL Server to know how to run lambda expressions.
Right now basically have this expression:
item => new MyClass
{
SomeValue = item.Name, // this was generated from some other code
AnotherValue = item.SomeOtherColumn, // there can be lots of these
AliasCount = p.Aliases.Count() // here of course is the problem
}
Obviously I want to replace the expression with the "p" when I am building this with the expression for item (which I have and know how to use).
TLDR Is there an easy way to replace all instances of a parameter usaged in a LambdaExpression with another Expression?