gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:28:14 25 4
gpt4 key购买 nike

在我们应用程序的许多不同查询中出现的一组特定条件逐渐变得越来越复杂。为避免重复此代码,我想将这些条件拆分为一个方法,该方法将条件作为 Expression 返回,然后可以在必要时应用:

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

这样重用:

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

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

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

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

最佳答案

这个问题有两个部分:

如何在 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();

关于c# - LINQ to Entities 查询中的可重用谓词表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17326321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com