Search code examples
c#linqentity-frameworkgenericsexpression-trees

How do I build a Linq Expression Tree that compares against a generic object?


I have an IQueryable and an object of type T.

I want to do IQueryable().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName))

so ...

public IQueryable<T> DoWork<T>(string fieldName)
        where T : EntityObject
{
   ...
   T objectOfTypeT = ...;
   ....
   return SomeIQueryable<T>().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName));
}

Fyi, GetProperty isn't a valid function. I need something which performs this function.

Am I having a Friday afternoon brain melt or is this a complex thing to do?


objectOfTypeT I can do the following ...

var matchToValue = Expression.Lambda(ParameterExpression
.Property(ParameterExpression.Constant(item), "CustomerKey"))
.Compile().DynamicInvoke();

Which works perfectly,now I just need the second part:

return SomeIQueryable().Where(o => o.GetProperty(fieldName) == matchValue);


Solution

  • Like so:

        var param = Expression.Parameter(typeof(T), "o");
        var fixedItem = Expression.Constant(objectOfTypeT, typeof(T));
        var body = Expression.Equal(
            Expression.PropertyOrField(param, fieldName),
            Expression.PropertyOrField(fixedItem, fieldName));
        var lambda = Expression.Lambda<Func<T,bool>>(body,param);
        return source.Where(lambda);
    

    I have started a blog which will cover a number of expression topics, here.

    If you get any problems, another option is to extract the value from objectOfTypeT first (using reflection) and then use that value in the Expression.Constant, but I suspect it'll be fine "as is".