LINQ to Entities查询中可重用的谓词表达式

ber*_*hof 6 c# linq-to-entities expression entity-framework predicatebuilder

在我们的应用程序中,许多不同查询中出现的一组标准已经慢慢变得更加复杂.为了避免重复此代码,我想将这些条件拆分为一个方法,该方法将条件作为表达式返回,然后可以在必要时应用它:

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

重复使用:

var result = repository.Invoice.Where(GetComplexPredicate())
Run Code Online (Sandbox Code Playgroud)

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

var result = repository.Customer
    .Where(c => c.Country == "US" && c.Invoice.Any(GetComplexPredicate()))
Run Code Online (Sandbox Code Playgroud)

是否可以使用这样的表达式?

ber*_*hof 7

这个问题分为两部分:

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

L2E允许在查询中使用AsQueryable扩展方法.这意味着我能够在转换的ICollection的IQueryable和应用谓词表达.到现在为止还挺好.但是,它可能会编译,但它仍然无法运行,因为L2E将不知道如何处理GetComplexPredicate方法中的预定义表达式.这导致我们:

如何将多个单独的谓词表达式合并为一个?

非常有用的LINQKit可以使用PredicateBuilder轻松地将多个谓词组合成一个表达式.使用LINQKit中的Expand方法和前面提到的AsQueryable,我们终于可以得到一个可以编译和运行的语句:

// 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();
Run Code Online (Sandbox Code Playgroud)