You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Web API:如何获取3天后结束休假的已审批员工

获取符合条件的员工列表实现方案

需求明确:筛选出休假结束日期在当前日期起3天内且**休假申请已批准(IsApproved=true)**的员工列表,以下是两种基于Entity Framework Core的实现方式:

方式一:从休假申请表关联查询

直接从LeaveApplication出发,筛选符合条件的申请后关联对应的员工,最后去重避免重复数据:

var currentDate = DateTime.Now.Date;
var threeDaysLater = currentDate.AddDays(3);

var eligibleEmployees = await _context.LeaveApplications
    .Where(la => la.IsApproved == true 
                 && la.EndDate.Date >= currentDate 
                 && la.EndDate.Date <= threeDaysLater)
    .Select(la => la.Employee)
    .Distinct()
    .ToListAsync();

方式二:从员工表关联休假申请查询

如果需要同时获取员工的休假申请信息,可以从Employee表入手,先关联休假申请再过滤:

第一步:完善Employee实体导航属性

首先需要在Employee类中添加一对多的导航属性,确保EF Core能识别关系:

public class Employee
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }

    // 新增导航属性,关联员工的所有休假申请
    public virtual ICollection<LeaveApplication> LeaveApplications { get; set; } = new List<LeaveApplication>();
}

第二步:编写查询逻辑

var currentDate = DateTime.Now.Date;
var threeDaysLater = currentDate.AddDays(3);

var eligibleEmployees = await _context.Employees
    .Include(e => e.LeaveApplications)
    .Where(e => e.LeaveApplications.Any(la => la.IsApproved == true 
                                              && la.EndDate.Date >= currentDate 
                                              && la.EndDate.Date <= threeDaysLater))
    .ToListAsync();

注意事项

  • 使用.Date属性可以忽略时间部分的干扰,确保仅按日期范围筛选;如果业务需要精确到时间,可去掉.Date。
  • 异步查询使用ToListAsync(),同步场景替换为ToList()即可。
  • 若使用方式二且仅需加载符合条件的休假申请,EF Core 5+支持直接在Include中过滤:
var eligibleEmployees = await _context.Employees
    .Include(e => e.LeaveApplications.Where(la => la.IsApproved == true 
                                                  && la.EndDate.Date >= currentDate 
                                                  && la.EndDate.Date <= threeDaysLater))
    .Where(e => e.LeaveApplications.Any())
    .ToListAsync();

内容的提问来源于stack exchange,提问作者Ayobamilaye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:40:31