可重复使用的谓词表达式LINQ to Entities查询 [英] Reusable predicate expressions in LINQ to Entities queries

查看:202
本文介绍了可重复使用的谓词表达式LINQ to Entities查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一组特定的标准,在我们的应用增长缓慢更复杂的出现在许多不同的查询。为了避免这种代码的重复,我想了拆分这些标准成返回的条件为表达反过来又能被应用在必要的方法:

A certain set of criteria that occurs in many different queries throughout our application has slowly grown more complex. To avoid duplication of this code, I want to split these criteria out into a method that returns the conditions as an Expression that can in turn be applied where necessary:

public Expression<Func<Invoice, bool>> GetComplexPredicate()
{
    // complex predicate is returned as an Expression:
    return c => ...
}



重用这样的:

Reused as such:

var result = repository.Invoice.Where(GetComplexPredicate())

但是,下面的语句不会编译,因为 c.Invoice 只是一个的ICollection

However, the statement below won't compile, since c.Invoice is just an ICollection.

var result = repository.Customer
    .Where(c => c.Country == "US" && c.Invoice.Any(GetComplexPredicate()))

时以任何可能的方式来使用这样的表达?

Is it in any way possible to use the expression like this?

推荐答案

有两个部分对这个问题:

There are two parts to this question:

我如何使用上的导航属性谓词表达式L2E查询中

L2E允许使用的 AsQueryable已 扩展在查询中的方法。这意味着,我可以转换的的ICollection 的IQueryable 并应用谓词表达。到现在为止还挺好。但是,它可能编译,但它仍然不会跑,因为L2E将不知道如何处理从GetComplexPredicate方法预定义的表达做。这使我们:

L2E allows the use of the AsQueryable extension method within a query. This means that I'm able to convert the ICollection to an IQueryable and apply the predicate expression. So far so good. However, it might compile, but it still won't run, since L2E won't know what to do with the predefined expression from the GetComplexPredicate method. This leads us to:

如何将几个独立的谓语表现为一个

在非常有益的 LINQKit 可以很容易地把几个谓词到使用 PredicateBuilder 的一种表现。凭借在扩展从LINQKit方法和前面提到的 AsQueryable已,我们可以在一个声明都将编译和精美的运行最后到达:

The enormously useful LINQKit can easily combine several predicates into one expression using PredicateBuilder. With the Expand method from LINQKit and the aforementioned AsQueryable, we can finally arrive at a statement that will both compile and run beautifully:

// build the entire predicate beforehand (PredicateBuilder + AsQueryable):
var complexPredicate = GetComplexPredicate();
var condition = PredicateBuilder.True<Customer>()
    .And(c => c.Country == "US")
    .And(c => c.Invoice.AsQueryable().Any(complexPredicate));

// apply criteria to query (using Expand):
var result = repository.Customer.Where(condition.Expand()).ToList();

这篇关于可重复使用的谓词表达式LINQ to Entities查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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