[英]How to write a generic expression tree for filter data in c#
嗨,我在c#中创建一个winform应用程序。
我使用EF5处理数据库。
并且为了将数据绑定到我的datagridviews,我从BindingSource创建了一个组件,该组件具有运行此事件的Bind()方法:
private object bindingSourceTbl1_DataSourceBinding(object sender, EventArgs e)
{
using (SampleDbEntities dbo = new SampleDbEntities())
{
return(from x in dbo.Tbl1
where x.Id == (int)comboBoxPerson.SelectedValue
select x).Take(1000).ToList();
}
}
因为我的数据库有很多大数据,我获取部分数据。 我用搜索获得匹配记录。 为此,我创建了一个SearchPanel组件,该组件创建了用于过滤网格中各列的文本框。
现在,我想将表达式树作为参数发送到我的事件,以加入到where子句中,如下所示:
private object bindingSourceTbl1_DataSourceBinding(object sender, EventArgs e,Expression whereClause)
{
using (SampleDbEntities dbo = new SampleDbEntities())
{
return(from x in dbo.Tbl1
where x.Id == (int)comboBoxPerson.SelectedValue && whereClause
select x).Take(1000).ToList();
}
}
但我的表达式树构建器方法存在于我的组件代码中,我不能访问我的项目中的DbContext,只是我的组件中有fieldNames,我也想为所有表编写一个方法。
这意味着我无法回归
表达式<Func <AnyDbSet,bool >>
我不知道怎么办?
谢谢
如果你只需要&&
,那么实现coll.Where(x => a(x) && b(x))
(其中a(x)
和b(x)
是任何与x
一起使用的布尔表达式)是有帮助的逻辑上与coll.Where(x => a(x)).Where(x => b(x))
相同coll.Where(x => a(x)).Where(x => b(x))
。 这意味着您可以将代码重写为:
List<Tbl1Type> GetTbl1Values(Expression<Func<Tbl1Type, bool>> whereClause)
{
using (SampleDbEntities dbo = new SampleDbEntities())
{
return dbo.Tbl1
.Where(x => x.Id == (int)comboBoxPerson.SelectedValue)
.Where(whereClause)
.Take(1000).ToList();
}
}
如果您还需要支持||
或者更复杂的组合,你可以使用LINQKit 。
这只是从属性名称创建表达式的问题。 您可以使用Expression
类型的方法。 例如,类似于:
static Expression<Func<T, bool>> CreateWhereClause<T>(
string propertyName, object propertyValue)
{
var parameter = Expression.Parameter(typeof(T));
return Expression.Lambda<Func<T, bool>>(
Expression.Equal(
Expression.Property(parameter, propertyName),
Expression.Constant(propertyValue)),
parameter);
}
您可以使用动态linq 。 这是一个例子:
var result = northwind.Products
.Where("CategoryID = 3 AND UnitPrice > 3")
.OrderBy("SupplierID");
===
private object bindingSourceTbl1_DataSourceBinding(object sender, EventArgs e,Expression whereClause)
{
using (SampleDbEntities dbo = new SampleDbEntities())
{
var q = from x in dbo.Tbl1
where x.Id == (int)comboBoxPerson.SelectedValue && whereClause
select x);
q = q.Where(whereClause)// your must reference dynamic linq library.
//whereClause is expression
.Take(100);
return q.ToList();
}
}
我建议使用Joseph Albahari的PredicateBuilder。 您可以在http://www.albahari.com/nutshell/predicatebuilder.aspx找到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.