Currently, I'm trying to use a LINQ expression to query a SQL database. The linq query works fine in LinqPad, however, I'm having a hard time figuring out how to form a query that will work in Visual Studio.
Here is the query in LINQPad5
Group_Employees.Where(x => x.EffectiveDate <= DateTime.Now && x.EndDate >= DateTime.Now && x.GroupId == 132 || x.GroupId == 134)
This returns 85 records (the correct number). However, when I try to use the same conditions in my C# program, I get 86 records.
My code looks like this:
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));
The final predicate assignment using k.EffectiveDate, etc., does not have any effect on the result set (I'm still getting 86 records instead of the 85).
EDIT: figured it out! I had to incorporate parenthesis so the following works:
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));
Thank you for your help!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.