如何重用哪里Linq中的条款SQL查询 [英] How to reuse where clauses in Linq To Sql queries

查看:97
本文介绍了如何重用哪里Linq中的条款SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有搜索的用户类型为Record的记录。他们键入搜索词中的一个文本框,然后我通过与搜索词匹配多个领域的搜索记录。

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。

如何重用我在这里穿过查询条件?

How can I reuse my where condition across queries?

推荐答案

使用一个<一个href="http://msdn.microsoft.com/en-us/library/system.data.linq.compiledquery.aspx">CompiledQuery!

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中的条款SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆