我如何动态创建以下LINQ表达式? [英] How do i create the following LINQ expression dynamically?
问题描述
我需要将以下C#代码转换为有效的实体框架6表达式:
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...
一般来说,我想要达到的是一个动态查询的形式,用户将在收藏箱中选择属性进行过滤,提供过滤器值和命中查询...通常人们喜欢 f => f.TargetProp == userValue
但是当我不知道它是哪一个的时候我不能这样做...
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);
}
这允许你写:
query = query.Where(PropertyEquals<EntityType>(stringParameter, anotherString));
这篇关于我如何动态创建以下LINQ表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!