我使用ASP MVC,我有这个LINQ让员工DTR:
IEnumerable<DatatablesViewModel> viewmodel =
(from a in db.tHREmployees
join b in db.tTADTRs on a.EmpID equals b.EmpID
join c in db.tHRJobGrades on a.JobGrdID equals c.JobGrdID
join d in db.tTAShifts on b.ShftID equals d.ShftID
join e in db.tTADays on b.DayID equals e.DayID
where (b.LogDt >= PeriodDates.FromDt && b.LogDt <= PeriodDates.ToDt)
select new DatatablesViewModel
{
EmpID = a.EmpID,
Name = a.LastNm + ", " + a.FirstNm + ", " + a.MiddleNm,
JobGradeDesc = c.JobGrdDesc,
ShftNm = d.ShftNm,
DayType = e.DayNm,
LogDT = b.LogDt,
LogIn = b.LogIn,
LogOut = b.LogOut,
Absent = b.AbsDay,
Work = b.WorkHr,
Late = b.LateHr,
Overtime = b.OTHr,
Undertime = b.OTHr,
Nightdiff = b.NDHr,
NightPrem = b.NPHr,
ApprovedOT = b.AppOT,
ApprovedOB = b.AppOB,
ApprovedCoa = b.AppCOA,
ApprovedCs = b.AppCS,
Exception = b.ExcptStatus
}).OrderBy(x => x.EmpID);
在我看来,我的下拉菜单的员工姓名带有'ALL'选项。 我想在上面代码中的'where'里面添加一个条件,如:
if(parameter.selectedEmp != "ALL"){
Where(x => x.EmpID == param.CustomParam_EmpID) <-- add this filter
}
我想只选择查询中需要的内容以避免延迟。
答案 0 :(得分:1)
您无需直接在Where
子句中添加它。只有在您开始遍历集合时,才会评估IEnumerable
和您的LINQ查询。你可以简单地做这样的事情:
var relevantVMObjects =
(from a in db.tHREmployees
join b in db.tTADTRs on a.EmpID equals b.EmpID
join c in db.tHRJobGrades on a.JobGrdID equals c.JobGrdID
join d in db.tTAShifts on b.ShftID equals d.ShftID
join e in db.tTADays on b.DayID equals e.DayID
where (b.LogDt >= PeriodDates.FromDt && b.LogDt <= PeriodDates.ToDt)
select new DatatablesViewModel
{
EmpID = a.EmpID,
Name = a.LastNm + ", " + a.FirstNm + ", " + a.MiddleNm,
JobGradeDesc = c.JobGrdDesc,
ShftNm = d.ShftNm,
DayType = e.DayNm,
LogDT = b.LogDt,
LogIn = b.LogIn,
LogOut = b.LogOut,
Absent = b.AbsDay,
Work = b.WorkHr,
Late = b.LateHr,
Overtime = b.OTHr,
Undertime = b.OTHr,
Nightdiff = b.NDHr,
NightPrem = b.NPHr,
ApprovedOT = b.AppOT,
ApprovedOB = b.AppOB,
ApprovedCoa = b.AppCOA,
ApprovedCs = b.AppCS,
Exception = b.ExcptStatus
}).OrderBy(x => x.EmpID);
if(parameter.selectedEmp != "ALL")
relevantVMObjects = relevantVMObjects.Where(x => x.EmpID == param.CustomParam_EmpID);
IEnumerable<DatatablesViewModel> viewmodel = relevantVMObjects;
答案 1 :(得分:0)
您可以通过OR
条件
string selectedEmp=parameter.selectedEmp;
IEnumerable<DatatablesViewModel> viewmodel =
(from a in db.tHREmployees
join b in db.tTADTRs on a.EmpID equals b.EmpID
join c in db.tHRJobGrades on a.JobGrdID equals c.JobGrdID
join d in db.tTAShifts on b.ShftID equals d.ShftID
join e in db.tTADays on b.DayID equals e.DayID
where (b.LogDt >= PeriodDates.FromDt && b.LogDt <= PeriodDates.ToDt) &&
(selectedEmp != "ALL" || a.EmpID == param.CustomParam_EmpID)
select new DatatablesViewModel
{
...
}