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

使用Entity Framework过滤三级关联ReservationUnit记录失效如何解决

问题原因

  1. 导航属性名拼写错误:Reservation类中定义的关联集合是ReservationUnits(复数形式),你编写的查询中使用了ReservationUnit(单数形式),EF无法识别该属性,导致过滤条件直接失效,返回全部关联数据。
  2. 导航属性定义缺失:你贴出的Reservation类代码中ReservationUnits属性缺少{ get; set; }定义,也可能导致导航属性加载异常。
  3. IncludeFilter调用逻辑问题:你先调用IncludeFilter(p => p.Reservation)完整加载了全部Reservation对象,后续对ReservationUnits的过滤无法覆盖已加载的全量数据。

解决方案

方案1:从Unit集合出发查询(保留原有查询逻辑)

修正属性名和IncludeFilter写法即可,EF Plus的IncludeFilter支持直接加载多级过滤后的关联数据:

var result = _unitOfWork.UnitRepository
    .GetBySessionIdAndUnit(sessionId, newUnitIds)
    .IncludeFilter(u => u.Reservation.ReservationUnits.Where(ru => ru.AmountIsTaxInclusive == true))
    .ToList();

该写法返回的Unit集合中,每个Unit关联的Reservation下只会保留AmountIsTaxInclusive为true的ReservationUnits记录。

方案2:直接查询ReservationUnit集合(性能更优)

如果你的需求是直接获取符合条件的ReservationUnit记录,不需要外层的Unit包裹,直接从ReservationUnit出发查询更高效,避免加载多余数据:

var filteredReservationUnits = _unitOfWork.ReservationUnitRepository
    .Where(ru => newUnitIds.Contains(ru.UnitID) && ru.AmountIsTaxInclusive == true)
    // 按需加载关联对象即可
    .Include(ru => ru.Unit)
    .Include(ru => ru.Reservation)
    .ToList();

补充说明

如果你使用的是EF Core 5及以上版本,框架原生支持过滤Include功能,不需要依赖EF Plus的IncludeFilter,写法如下:

var result = _unitOfWork.UnitRepository
    .GetBySessionIdAndUnit(sessionId, newUnitIds)
    .Include(u => u.Reservation)
    .Include(u => u.Reservation.ReservationUnits.Where(ru => ru.AmountIsTaxInclusive == true))
    .ToList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:21:01