我使用此搜索功能时出现一些错误。我有两个表:员工和出勤。在表
Attendance
中有 AddendanceDate
(日期时间)列。我想得到今天缺席员工名单的结果。对于 DateTime.Today
结果还可以,但我想选择其他日期的搜索关键字。
如何在以下代码中进行分配?
public async Task<IEnumerable<AbsentReportsViewModel>> GetAllAbsentEmpAsync(DateTime date)
{
var query = await (from e in _dbContext.Employees
join attt in _dbContext.Attendances
on e.Id equals attt.EmployeeId into eGroup
from eattt in eGroup.Where(a => a.AttendanceDate == DateTime.Today ).DefaultIfEmpty()
where eattt.AttendanceDate == null
select new AbsentReportsViewModel
{
JobId = e.JobId,
EmpReportName = e.NameMM,
DeptId = e.DeptId,
RankId = e.CurrentRankId,
DeptReportName = e.Department.DeptName,
RankReportName = e.Rank.RankName,
BarCode = e.Barcode,
EmpReportId = e.Id,
}).ToListAsync();
return query;
}
我试过了:
... a.AttendanceDate == date.DefaultIfEmpty(),
... a.AttendanceDate == ((date).Year, (date).Month, (date).Day).DefaultIfEmpty()
我没有得到想要的结果。
请帮我看看路。谢谢!
为了确保日期属于当前日期,最好使用范围过滤器。它将强制 SQL Server 使用索引。
LEFT JOIN
表示也可以简化:
var startDate = DateTime.Today.Date;
var endDate = startDate.AddDays(1);
var query =
from e in _dbContext.Employees
from eattt in _dbContext.Attendances
.Where(a => a.EmployeeId == e.Id && a.AttendanceDate >= startDate && a.AttendanceDate < endDate)
.DefaultIfEmpty()
where eattt.AttendanceDate == null
select new AbsentReportsViewModel
{
JobId = e.JobId,
EmpReportName = e.NameMM,
DeptId = e.DeptId,
RankId = e.CurrentRankId,
DeptReportName = e.Department.DeptName,
RankReportName = e.Rank.RankName,
BarCode = e.Barcode,
EmpReportId = e.Id,
};