1

I need the following C# code to be translated to a valid Entity Framework 6 expression:

(f => f.GetType().GetProperty(stringParamter).GetValue(f).ToString() == anotherStringParameter)

This guy did it for the "Order By" part, but i cant seem to figure it out for the "where" part...

Generically speaking what i am trying to achieve here is a form of dynamic query where the user will "pick" properties to filter in a "dropbox", supply the filter-value and hit query... usually people do like f => f.TargetProp == userValue but i can't do that when i dont know which one it is...

Community
  • 1
  • 1
Leonardo
  • 10,737
  • 10
  • 62
  • 155

2 Answers2

6

You need to construct the expression tree that represents the access to the property:

public static Expression<Func<T, bool>> PropertyEquals<T>(
    string propertyName, string valueToCompare)
{
    var param = Expression.Parameter(typeof(T));
    var body = Expression.Equal(Expression.Property(param, propertyName)
        , Expression.Constant(valueToCompare));
    return Expression.Lambda<Func<T, bool>>(body, param);
}

This allows you to write:

query = query.Where(PropertyEquals<EntityType>(stringParameter, anotherString));
Servy
  • 202,030
  • 26
  • 332
  • 449
  • what if i want to compare to a fixed/pre-determined sub-property? like: instead of `Expression.Property(param, propertyName)` something like `Expression.Property(param, propertyName.Title)` – Leonardo Apr 07 '14 at 17:07
  • @Leonardo Then use two `Expression.Property` calls to access the fixed property of the result of the previous property access. – Servy Apr 07 '14 at 17:08
1

Have you considered using the Dynamic Link Library? It allows you to compose expressions as strings instead of lambda expressions.

Examples:

var query = baseQuery.Where("Id=5");

var query = baseQuery.Where("Id=@0", 5);

I've been keeping an updated version of Microsoft's Dynamic Linq example at https://github.com/NArnott/System.Linq.Dynamic in case you are interested, and it's also available on NuGet.

Nathan A
  • 11,059
  • 4
  • 47
  • 63