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

Razor Page查询中如何仅提取日期而非DateTime

解决单日期查询单日全时段记录的问题

1. 调整输入参数与模型字段

首先把原有的起止日期相关字段替换为单个日期字段,简化输入逻辑:

public Trip Trip { get; set; }
public Client Client { get; set; }
public DateTime? SelectedDate { get; set; } // 替换原StartDate、EndDate
public PaginatedList<ReportModel> ScheduledTrips { get; set; } = default!; 

2. 修改OnGet方法参数与查询逻辑

将方法参数改为单个日期,再通过该日期构造当日的时间范围进行过滤(这种方式能最大化利用PickUpDateTime字段的索引,性能更优):

public async Task OnGet(DateTime? selectedDate, int? pageIndex)
{
    SelectedDate = selectedDate;

    IQueryable<ReportModel> scheduledTrips = from x in _context.Trip
                                            join y in _context.Client on x.ClientName equals y.DisplayName
                                            orderby x.PickUpDateTime
                                            select new ReportModel(/* 你的原有对象构造逻辑 */);

    // 仅当选中日期不为空时添加过滤条件
    if (SelectedDate.HasValue)
    {
        DateTime dayStart = SelectedDate.Value.Date; // 当日00:00:00
        DateTime dayEnd = dayStart.AddDays(1); // 次日00:00:00
        scheduledTrips = scheduledTrips.Where(x => x.PickUpDateTime >= dayStart && x.PickUpDateTime < dayEnd);
    }

    // 原有分页逻辑保持不变
    ScheduledTrips = await PaginatedList<ReportModel>.CreateAsync(scheduledTrips, pageIndex ?? 1, /* 你的分页大小 */);
}

备选方案(不推荐用于大数据量)

如果业务场景特殊,也可以直接对比日期部分,但这种写法可能无法利用索引,数据量大时性能会下降:

// 仅作为备选,优先用上面的时间范围方式
if (SelectedDate.HasValue)
{
    DateTime targetDate = SelectedDate.Value.Date;
    scheduledTrips = scheduledTrips.Where(x => x.PickUpDateTime.Date == targetDate);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 23:32:34