gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:00:53 24 4
gpt4 key购买 nike

您好,我在 C# 中创建了一个 winform 应用程序。

我使用 EF5 来处理数据库。

为了将数据绑定(bind)到我的数据 GridView ,我从 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,而且我只想为所有表编写一个方法。

这意味着我不能返回

Expression< Func< AnyDbSet,bool>>

我不知道怎么做?

谢谢

最佳答案

如果您只需要 &&,那么了解 coll.Where(x => a(x) && b(x))(其中 a(x)b(x) 是与 x 一起使用的任何 bool 表达式) 在逻辑上与 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);
}

关于c# - 如何在 C# 中为过滤数据编写通用表达式树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19970278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com