如何基于目的地ID计算各目的地Pax总和(代码结果异常)
问题分析
当前代码里,各目的地的Pax字段计算仅按日期过滤了预订数据,未关联对应目的地ID,导致所有目的地的Pax都取了当天所有预订的总人数,出现数值一致的错误。而TotalPax因为是统计当天所有预订总和,所以结果正确。
修正后代码
public async Task<IEnumerable<ReservationCalendarGroupVM>> GetForCalendarAsync(string fromDate, string toDate) { var startDate = Convert.ToDateTime(fromDate); var endDate = Convert.ToDateTime(toDate); return await context.Schedules .AsNoTracking() .Where(x => x.Date >= startDate && x.Date <= endDate) .GroupBy(z => z.Date) .Select(e => new ReservationCalendarGroupVM { Date = e.Key.Date.ToString(), Destinations = e.GroupBy(i => new { i.Destination.Id, i.Destination.Abbreviation, i.Destination.Description }) .Select(p => new DestinationCalendarVM { Id = p.Key.Id, Abbreviation = p.Key.Abbreviation, Description = p.Key.Description, // 新增目的地ID过滤,统计当天该目的地的总人数 Pax = context.Reservations.Where(y => y.Date == e.Key.Date && y.DestinationId == p.Key.Id).Sum(h => h.TotalPersons) }), TotalPax = context.Reservations.Where(y => y.Date == e.Key.Date).Sum(h => h.TotalPersons) }).ToListAsync(); }
关键修改说明
- 把日期转换逻辑提取到外部,避免重复转换,提升代码可读性
- 在
Pax的计算逻辑中,新增y.DestinationId == p.Key.Id条件,确保仅统计当前分组目的地的预订人数
另外,若你的Reservation实体与Schedule实体有关联(比如Reservation包含ScheduleId),也可以通过分组的p(即同日期同目的地的Schedule集合)关联预订,利用EF的关联查询优化性能:
Pax = p.SelectMany(s => s.Reservations).Sum(r => r.TotalPersons)
前提是Schedule实体中已配置Reservations导航属性。
内容的提问来源于stack exchange,提问作者John Sourvinos
相关产品推荐
相关产品推荐

