How do i create the following LINQ expression dynamically?

折月煮酒 提交于 2019-12-11 11:17:18

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/22916231/how-do-i-create-the-following-linq-expression-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!