Linq-to-SQL将两个Expression <Func <T,bool >>("where子句")与和/或组合在一起

Fra*_* CD 5 c# linq linq-to-sql

首先,我必须说我已经在StackOverflow上阅读了几篇有关此内容的帖子,但我无法获得所需的结果.

让我解释上下文(简化):我使用Linq-to-SQL来查询最近访问商店的客户,并(可选)只获得具有一定金额的付款.假设我有一个客户端,访问和付款类的模型.

所以,专注于Where表达,我正在尝试这个:

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

filter.And方法是一种扩展方法,在本论坛推荐,下面你可以看到定义:

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

但是,这对我不起作用,并且结果不会按付款金额进行过滤.数据或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;
Run Code Online (Sandbox Code Playgroud)

但是,我不想使用最后一个代码,因为我有一些更复杂的场景,我需要使用每个部分的'和/或'组合逐步构建过滤器表达式.

PD:我是一个"ADO.Net DataSets",试图学习Linq-to-SQL和很快实体框架,我希望很快对StackOverflow社区有用.

Kri*_*izz 4

您没有将Anding 的结果分配给任何东西。

我想你的代码的相应部分应该如下所示:

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

问题是你的(或你提到的SO)And函数返回包含两个表达式的合取的表达式。它不会改变调用它的对象。