How do i create the following LINQ expression dyna

2019-08-03 07:37发布

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

2条回答
Root(大扎)
2楼-- · 2019-08-03 08:25

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-08-03 08:38

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));
查看更多
登录 后发表回答