Let's use this method that I'm trying to call as an example:
MyMethod<MyType, string>(Expression<Func<MyType, string>> expression)
If I try to dynamically build the following expression x => x.Name
and pass it to the method, everything works just fine:
var pi = typeof(MyType).GetProperty("Name");
ParameterExpression pe = Expression.Parameter(typeof(MyType), "x");
MemberExpression me = Expression.Property(pe, pi);
var exp = Expression.Lambda(me, pe);
Now let's imagine that in the exact same scope, I'm trying to build this expression instead x => item.Name
using the following code, obviously item being different than the input parameter x:
var item = new MyType() { Name = "My name" };
var pi = t.GetProperty("Name");
ParameterExpression pe = Expression.Parameter(typeof(MyType), "x");
ParameterExpression pe2 = Expression.Parameter(typeof(MyType), "item");
MemberExpression me = Expression.Property(pe2, pi);
var exp = Expression.Lambda(me, pe);
When I try to call MyMethod I get the following error, probably because there's no variable "item" in the scope where MyMethod is called (which is not where I build the expression):
variable 'item' of type 'MyType' referenced from scope '', but it is not defined
How can I build this expression in such a way that it won't throw this error?