Linq-to-SQL combining two expressions <Func <T, bool >> ("where where") with and / or

First, I have to say that I read a few posts about this in StackOverflow, but I can’t get the desired result.

Let me explain the context (simplified): I use Linq-to-SQL to query customers with recent visits to the store and (optionally) receive only those with a certain amount of payments. Suppose I have a model with classes of customers, visits and payments.

So, focusing on the expression Where, I try this:

Expression<Func<Entityes.Clients, bool>> filter = null;

filter = c => 
          c.Visits.Any(v => v.VisitDate > DateTime.Now.Date.AddMonths(-(int)visitsSince));


if (minPayment.HasValue && minPayment.Value > 0)
{
     filter.And(
               c => c.Payments.Sum(p => p.Quantity) > minPayment.Value);
}

Method filter.Andis an extension method recommended in this forum, below you can see the definition:

public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expression1,
                                            Expression<Func<T, bool>> expression2)
{
  InvocationExpression invokedExpression =
      Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());

  return Expression.Lambda<Func<T, bool>>
      (Expression.And(expression1.Body, invokedExpression), expression1.Parameters);
}

, , . linq-to-sql , :

filter = c => 
           c.Visits.Any(v => v.VisitDate > DateTime.Now.Date.AddMonths(-(int)visitsSince)))
             && c => c.Payments.Sum(p => p.Quantity) > minPayment.Value;

, , "/" .

PD: "ADO.Net DataSets", Linq-to-SQL Entity Framework, , StackOverflow.

+5
3

And -.

, :

if (minPayment.HasValue && minPayment.Value > 0)
{
   filter = filter.And(
            c => c.Payments.Sum(p => p.Quantity) > minPayment.Value);
}

, ( SO, ) And function , . , .

+3

:

filter.And(c => c.Payments.Sum(p => p.Quantity) > minPayment.Value); 

And , . :

filter = filter.And(c => c.Payments.Sum(p => p.Quantity) > minPayment.Value); 

, And - , . , , . filter.And(...), , filter -.

+1

All Articles