How to reuse where clauses in Linq To Sql queries(如何在 Linq To Sql 查询中重用 where 子句)
问题描述
我有用户搜索记录类型的记录.他们在文本框中键入搜索词,然后我通过将多个字段与搜索词匹配来搜索记录.
I have users searching records of type Record. They type a search term in a textbox and then I search records by matching several fields with the search term.
我的查询看起来像:
var results = from record in DataContext.Records
where
record.Field1.ToLower().Contains(term) ||
record.Field2.ToLower().Contains(term) ||
record.Field3.ToLower().Contains(term)
select record;
我有许多查询都使用相同的过滤器,因此我想提取过滤器以便可以重复使用.类似的东西:
I have a number of queries that all use the same filter and thus I would like to extract the filtering so it can be reused. Something like:
var filter = new Func<Record, string, bool>(
(record, term) =>
record.Field1.ToLower().Contains(term) ||
record.Field2.ToLower().Contains(term) ||
record.Field3.ToLower().Contains(term)
);
var results = from record in DataContext.Records
where filter(record, term)
select record;
然而,它不起作用,因为:
However, it does not work because:
方法System.Object DynamicInvoke(System.Object[])"不支持转换为 SQL.
如何在查询中重复使用我的 where 条件?
How can I reuse my where condition across queries?
推荐答案
使用 编译查询!
var filter = CompiledQuery.Compile(
(DatabaseDataContext dc, Record record, string term) =>
record.Field1.ToLower().Contains(term) ||
record.Field2.ToLower().Contains(term) ||
record.Field3.ToLower().Contains(term)
);
var results = from record in DataContext.Records
where filter(DataContext, record, term)
select record;
有关详细信息,请参阅如何:存储和重用查询.
For more information, see How to: Store and Reuse Queries.
这篇关于如何在 Linq To Sql 查询中重用 where 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Linq To Sql 查询中重用 where 子句


基础教程推荐
- 从 VB6 迁移到 .NET/.NET Core 的最佳策略或工具 2022-01-01
- 当键值未知时反序列化 JSON 2022-01-01
- Page.OnAppearing 中的 Xamarin.Forms Page.DisplayAlert 2022-01-01
- 创建属性设置器委托 2022-01-01
- 使用 SED 在 XML 标签之间提取值 2022-01-01
- C# - 将浮点数转换为整数...并根据余数更改整数 2022-01-01
- 我什么时候应该使用 GC.SuppressFinalize()? 2022-01-01
- 覆盖 Json.Net 中的默认原始类型处理 2022-01-01
- C# - 如何列出发布到 ASPX 页面的变量名称和值 2022-01-01
- 如何使用OpenXML SDK将Excel转换为CSV? 2022-01-01