好的,我有一个带有巨大表的数据库。超过 100 万条记录和 50 多个列。 (我知道它不是最佳的,但它是我必须处理的)所以我需要运行限制返回数据量的查询。现在我的问题是这样的。我有一些运行并返回数据的自定义查询。用户可以通过选择将生成谓词模板并将其应用到列表的过滤器和选项来进一步过滤该数据。我现在需要获取谓词列表并将它们组合起来并重新查询数据库以搜索(更改或其他条目匹配)。问题是这样的
private Func<table,bool> filterAll()
{
Func<table, bool> temp = null;
var list = mylist.filterList; //filterlist is a list<Predicate<table>>
var list2 = list.Select(val => val.Value).ToArray();
foreach(var a in list2)
{
temp += t => a(t);
}
return temp;
}
private void loadWithFiltersButton_Click(object sender, EventArgs e)
{
var temp = db.table.Where(filterAll());
}
我无法将谓词转换为可用的 sql 查询。我收到一个异常,说它无法为谓词列表生成 sql。我也尝试过这个
Func<table, bool> query1 = temp2 => temp2.Name.Contains("test string");
Func<table, bool> query2 = temp2 => temp2.ignore == false;
var temp = db.table.Where(query1);
var myval = temp.Where(temp2 => temp2.Name.Contains("test string")).Select(val => val).ToList();
虽然这确实执行了问题,但生成的 sql 会下拉整个表,并且根本不会生成 where 子句。
我一直在寻找并找到了这个https://stackoverflow.com/questions/974719/how-to-use-linq-to-compile-a-lambda-expression-to-custom-sql-or-otherwise https://stackoverflow.com/questions/974719/how-to-use-linq-to-compile-a-lambda-expression-to-custom-sql-or-otherwise但人们在答案中发布的所有链接对我来说都是死的。
那么基本上如何将多个谓词组合成一个可用的查询,以使数据库返回尽可能少的数据量?
编辑:也尝试过这个在 C# 中连接 Lambda 函数 https://stackoverflow.com/questions/491780/concatenating-lambda-functions-in-c-sharp但也会抛出无法生成sql查询的异常。