繁体   English   中英

将predicateBuilder与.Where方法一起使用

[英]Use predicateBuilder with .Where method

当前,我正在尝试使用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条记录)。

编辑:弄清楚了! 我必须合并括号,以便进行以下工作:

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));

谢谢您的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM