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...
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));
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.