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

Entity Framework Core查询构建问题:筛选符合条件的配送公司及最优车辆

问题解决:筛选符合条件的配送公司及对应最低价可用车辆

需求说明

  • 基于三个数据库关联实体类,实现方法返回满足用户条件的配送公司列表
  • 用户可指定筛选条件:minPrice(最低价格)、maxPrice(最高价格)、Weight(货物重量)、Volume(货物体积)、receiptDate(取货日期)、deliveryDate(送货日期)
  • 每个配送公司仅返回其所有符合条件的车辆中价格最低的一辆
  • 关键约束:车辆在receiptDate和deliveryDate这两个日期不能存在已预订记录

实体类定义

public class Delivery
{
    [Key]
    public int ID { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public int AvgEarnings { get; set; }

    public List<Vehicle> Vehicles { get; set; }
}

public class Vehicle
{
    [Key]
    public int ID { get; set; }

    [Required]
    public int MaxWeight { get; set; }

    [Required]
    public int MaxVolume { get; set; }

    [Required]
    public int Price { get; set; }

    [JsonIgnore]
    public Delivery Delivery { get; set; }

    public List<Reservation> Reservations { get; set; }
}

public class Reservation
{
    [Key]
    public int ID { get; set; }

    [Required]
    public DateTime Date { get; set; }

    [Required]
    public Vehicle Vehicle { get; set; }
}

现有代码问题

你尝试的代码中,!p.Reservations.Contains(receiptDate)写法错误——Reservations是Reservation对象的集合,不是DateTime类型集合,无法直接用Contains匹配日期值。需要检查集合中是否存在Date属性等于指定日期的预订记录。

正确实现代码

// 假设weight、volume、minPrice、maxPrice、receiptDate、deliveryDate为方法传入参数
var eligibleDeliveryCompanies = Context.Vehicles
    // 预加载关联的配送公司和预订记录
    .Include(v => v.Delivery)
    .Include(v => v.Reservations)
    // 筛选符合基础条件且指定日期无预订的车辆
    .Where(v => v.MaxWeight >= weight
             && v.MaxVolume >= volume
             && v.Price >= minPrice
             && v.Price <= maxPrice
             // 检查取货日期无预订(仅比较日期部分,忽略时间)
             && !v.Reservations.Any(r => r.Date.Date == receiptDate.Date)
             // 检查送货日期无预订
             && !v.Reservations.Any(r => r.Date.Date == deliveryDate.Date))
    // 按所属配送公司分组
    .GroupBy(v => v.Delivery)
    // 每组取价格最低的可用车辆
    .Select(g => new 
    {
        DeliveryCompany = g.Key,
        CheapestVehicle = g.OrderBy(v => v.Price).FirstOrDefault()
    })
    // 过滤掉没有可用车辆的配送公司
    .Where(result => result.CheapestVehicle != null)
    .ToList();

关键说明

  1. 日期检查:用Any()方法替代Contains(),判断Reservations集合中是否存在指定日期的预订;使用Date.Date确保只比较日期部分,避免时间精度导致的误判
  2. 分组取最低价:通过GroupBy按配送公司分组后,用OrderBy(v => v.Price).FirstOrDefault()获取每组价格最低的车辆
  3. 数据预加载:使用Include()预加载关联的Delivery和Reservations,避免N+1查询问题

内容的提问来源于stack exchange,提问作者Ракићевић Димитрије

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:25:22