【问题标题】:Use predicateBuilder with .Where method将 predicateBuilder 与 .Where 方法一起使用
【发布时间】:2018-01-15 22:26:44
【问题描述】:

目前,我正在尝试使用 LINQ 表达式来查询 SQL 数据库。 linq 查询在 LinqPad 中运行良好,但是,我很难弄清楚如何形成可以在 Visual Studio 中运行的查询。

这是 LINQPad5 中的查询

Group_Employees.Where(x => x.EffectiveDate <= DateTime.Now && x.EndDate >= DateTime.Now && x.GroupId == 132 || x.GroupId == 134)

这将返回 85 条记录(正确的数量)。但是,当我尝试在我的 C# 程序中使用相同的条件时,我得到了 86 条记录。

我的代码如下所示:

var predicate = PredicateBuilder.True<TimesheetLineItem>();

                if (startDate.HasValue)
                {
                    predicate = predicate.And(x => x.Date >= startDate);
                }

                if (weekendingdate.HasValue)
                {
                    predicate = predicate.And(x => x.Date <= weekendingdate);
                }

                else
                {
                    predicate = predicate.And(x => x.JobNumberCoding != null || x.JobNumberEquipmentGeneralLedgerDistribution != null || x.EquipmentCollection != null);
                }

                predicate = predicate.And(x => x.Timesheet.DivisionId == (int)Divisions.MPM);

                predicate = predicate.And(x => x.Timesheet.Employee.Group_Employee.Any(j => j.GroupId == 132 || j.GroupId == 134));

            predicate = predicate.And(x => x.Timesheet.Employee.Group_Employee.Any(k => k.EffectiveDate <= DateTime.Now && k.EndDate >= DateTime.Now));

使用 k.EffectiveDate 等的最终谓词赋值对结果集没有任何影响(我仍然得到 86 条记录而不是 85 条)。

【问题讨论】:

  • 您的 LINQPad 查询似乎缺少代码中的许多条件 - DivisionId 怎么样?
  • @NetMage 感谢您的及时回复。我实际上不认为附加条件对结果集有太大影响。直到倒数第二个谓词的所有内容(即谓词 = predicate.And(x => x.Timesheet.Employee.Group_Employee.Any(j => j.GroupId == 132 || j.GroupId == 134));)似乎工作正常,但是,当我尝试根据日期字段进行过滤时,对结果集没有影响。我觉得我需要找到一种方法来使用 .Where 而不是 .Any 进行最终的谓词分配。希望这有点道理。 :-/
  • 好吧,您的 LINQPad 查询似乎也反对 Group_Employees,但您的谓词构建器反对 TimesheetLineItem 那么您要过滤哪个?
  • @NetMage 你说得对,我的 LINQPad 查询是针对 Group_Employees 运行的,但是,在构建谓词的代码块中,我最终会深入到 Group_Employee 表并应用EffectiveDate 和 EndDate 字段的条件。这一行: predicate = predicate.And(x => x.Timesheet.Employee.Group_Employee.Any(j => j.GroupId == 132 || j.GroupId == 134 && j.EffectiveDate = DateTime.Now));对结果集没有任何影响,但我想我至少会少一个结果。

标签: c# linq linq-to-sql predicatebuilder


【解决方案1】:

编辑:想通了!我必须加上括号,所以以下工作:

predicate = predicate.And(x => x.Timesheet.Employee.Group_Employee.Any(y => (y.GroupId == 134 || y.GroupId == 132) && y.EffectiveDate <= DateTime.Now && y.EndDate >= DateTime.Now));

感谢您的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 2016-05-06
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多