【问题标题】:Invoke a C# inner Expression with a member property of a parameter to an outer expression使用外部表达式的参数的成员属性调用 C# 内部表达式
【发布时间】:2010-11-16 19:47:37
【问题描述】:

我正在使用此处http://www.albahari.com/nutshell/predicatebuilder.aspx 中的 Albaharis PredicateBuilder 来过滤 Linq-to-SQL 应用程序中的结果。这一直很好。

我现在要做的是重用现有的过滤谓词表达式来过滤具有现有过滤对象作为属性的对象。

例如,我有 2 个类,OrderCustomer。我已经有一个返回Expression<Func<Customer, bool>> 的方法,它是使用上述谓词构建器构建的。我现在想在我的Order 过滤方法中重用它,这将通过某种方式将Order.Customer 属性(表达式?)传递给我的Customer 过滤方法来返回Expression<Func<Customer, bool>>

我有这样的东西(远未完成,但我希望你明白):

public class CustomerSearchCriteria
{
    public Expression<Func<Customer, bool>> FilterPredicate()
    {
        // Start with predicate to include everything
        var result = PredicateBuilder.True<Customer>();

        // Build predicate from criteria
        if (!String.IsNullOrEmpty(this.Name))
        {
            result = result.And(c => SqlMethods.Like(c.Name, this.Name));
        }

        // etc. etc. etc

} 


public class OrderSearchCriteria
{
    public Expression<Func<Order, bool>> FilterPredicate()
    {
        // Start with predicate to include everything
        var result = PredicateBuilder.True<Order>();

        // Build predicate from criteria
        if (!String.IsNullOrEmpty(this.Reference))
        {
            result = result.And(o => SqlMethods.Like(o.Reference, this.Reference));
        }

        // etc. etc. etc
        // This is where I would like to do something like:
        // result = result.And(o => o.Customer "matches" this.CustomerCriteria.FilterPredicate()
} 

哪位Linq表达式大师可以帮帮我?

提前致谢。

【问题讨论】:

    标签: c# linq-to-sql lambda expression-trees


    【解决方案1】:

    如果您使用 Albaharis 的LinqKit,您应该可以执行以下操作:

    var customerFilter = this.CustomerCriteria.FilterPredicate();
    // create an expression that shows us invoking the filter on o.Customer
    Expression<Func<Order, bool>> customerOrderFilter = 
        o => customerFilter.Invoke(o.Customer);
    // "Expand" the expression: this creates a new expression tree
    // where the "Invoke" is replaced by the actual predicate.
    result = result.And(customerOrderFilter.Expand())
    

    【讨论】:

    • 非常感谢。这正是我需要的。我正在使用 PredicateBuilder,但没有包含或查看 LinqKit 的其余部分。
    猜你喜欢
    • 2017-11-12
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 2019-10-12
    相关资源
    最近更新 更多