So, I'm trying to figure out expression trees. I am trying to add the dynamic equivalent of Queryable, where T is one of several different tables. First, I check that the table contains a field in which I want to include a filter.
ParameterExpression param = Expression.Parameter(typeof(TSource), "x");
Expression conversionExpression = Expression.Convert(Expression.Property(param, _sourceProperty), typeof(TList));
Expression<Func<TSource, TList>> propertyExpression = Expression.Lambda<Func<TSource, TList>>(conversionExpression, param);
Expression<Func<TList, TList, bool>> methodExpression = (x, y) => x.Equals(y);
ReadOnlyCollection<ParameterExpression> parameters = propertyExpression.Parameters;
InvocationExpression getFieldPropertyExpression = Expression.Invoke(
propertyExpression,
parameters.Cast<Expression>());
MethodCallExpression methodBody = methodExpression.Body as MethodCallExpression;
MethodCallExpression methodCall = Expression.Call(methodBody.Method, Expression.Constant(equalTo), getFieldPropertyExpression);
Expression<Func<TSource, bool>> equalsStatement = Expression.Lambda<Func<TSource, bool>>(methodCall, parameters);
return source.Where(equalsStatement);
When I do this, I have a problem with MethodInfo in the Call statement. This tells me:
The static method requires a null instance, the non-static method requires a non-empty instance.
I am not the owner of expression trees, but I think I understand about 75% of what I am doing here and I know what I'm trying to achieve. TList is a bad name right now, but I took it from an example that works to make the In statement just great.
I'm really looking for an explanation here, so I can work with the code myself, or with an explanation of what I was missing.
Edit:
, , , , , .
ParameterExpression sourceObject = Expression.Parameter(typeof(TSource), "x");
Expression<Func<TSource, bool>> check = Expression.Lambda<Func<TSource, bool>>
(
Expression.Equal(
Expression.MakeMemberAccess(sourceObject, typeof(TSource).GetProperty(_sourceProperty)),
Expression.Constant(equalTo)
),
sourceObject
);
return source.Where(check);
- , , ? , , , .