目前,我正在尝试使用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条记录)。
答案 0 :(得分:0)
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));
感谢您的帮助!