如何在c#中为过滤数据编写通用表达式树

Ali*_*avi 2 c# entity-framework expression-trees

嗨我在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();
    }
}
Run Code Online (Sandbox Code Playgroud)

因为我的数据库有很多大数据,我获取部分数据.我用搜索获得匹配记录.为此,我创建了一个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();
    }
}
Run Code Online (Sandbox Code Playgroud)

但我的表达式树构建器方法存在于我的组件代码中,我不能访问我的项目中的DbContext,只是我的组件中有fieldNames,我也想为所有表编写一个方法.

这意味着我无法回归

表达式<Func <AnyDbSet,bool >>

我不知道怎么办?

谢谢

svi*_*ick 7

如果你只是需要&&,那么实现coll.Where(x => a(x) && b(x))(在哪里a(x)b(x)任何使用的布尔表达式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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您还需要支持||或更复杂的组合,您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)