C# 生成表达式<&燃气轮机;用于按任意属性进行筛选
我想写一个过滤控件,它接受对象类型C# 生成表达式<&燃气轮机;用于按任意属性进行筛选,c#,linq,dynamic,properties,filtering,C#,Linq,Dynamic,Properties,Filtering,我想写一个过滤控件,它接受对象类型T和属性名,并返回检查传递属性值的表达式。我不想使用反射,因为我担心EF不能使用这些表达式。我不能使用委托,因为C#没有属性的委托。我能做什么?也许我应该使用不同的方法来编写这些控件 以下是我使用反射的第一种方法: public string FilteringField { get; set; } public Expression<Func<T, bool>> GetFilterExpression() { if (cmbValu
T
和属性名,并返回检查传递属性值的表达式。我不想使用反射,因为我担心EF不能使用这些表达式。我不能使用委托,因为C#没有属性的委托。我能做什么?也许我应该使用不同的方法来编写这些控件
以下是我使用反射的第一种方法:
public string FilteringField { get; set; }
public Expression<Func<T, bool>> GetFilterExpression()
{
if (cmbValue.SelectedIndex == 1)
return (o => (bool)typeof(T).GetProperty(FilteringField).GetValue(o, null));
if (cmbValue.SelectedIndex == 2)
return (o => !(bool)typeof(T).GetProperty(FilteringField).GetValue(o, null));
return null;
}
公共字符串筛选器字段{get;set;}
公共表达式GetFilterExpression()
{
如果(cmbValue.SelectedIndex==1)
返回(o=>(bool)typeof(T).GetProperty(FilteringField).GetValue(o,null));
如果(cmbValue.SelectedIndex==2)
返回(o=>!(bool)typeof(T).GetProperty(FilteringField).GetValue(o,null));
返回null;
}
反射在这里不是问题;英孚甚至不会注意到其中的差异。顺便说一句,代理方法是一种非启动方法(因为您提到了EF);归根结底,这就像:
public static IQueryable<T> Where<T>(this IQueryable<T> query,
string propertyName, object value)
{
PropertyInfo prop = typeof(T).GetProperty(propertyName);
var param = Expression.Parameter(typeof(T), "x");
var body = Expression.Equal(
Expression.Property(param, prop),
Expression.Constant(value, prop.PropertyType)
);
var predicate = Expression.Lambda<Func<T, bool>>(body, param);
return query.Where(predicate);
}
公共静态IQueryable Where(此IQueryable查询,
字符串属性名称(对象值)
{
PropertyInfo prop=typeof(T).GetProperty(propertyName);
var param=表达式参数(类型(T),“x”);
var body=表达式。等于(
表达式.属性(参数,属性),
Expression.Constant(值,prop.PropertyType)
);
var谓词=Expression.Lambda(body,param);
返回query.Where(谓词);
}
请注意,您可以使用Expression.PropertyOrField(propertyName)
使其更简单;我没有在这里使用它的原因是,在创建常量时,知道成员类型(prop.PropertyType
)非常方便,否则您可能会遇到空值问题。我知道这是一个古老的答案,但如果有人看到这一点,我构建了这个项目:
也可以在nuget上下载:
你也可以这么做
query.Where("FirstName", ConditionOperators.Equal, "David");
你能澄清你的问题吗?你能举个例子吗?