首页 > 解决方案 > 无法翻译 LINQ 子查询 Where 子句

问题描述

我在 EF Core 2.2 中将此查询转换为 linq,但我找不到任何正确的方法:

select r.*,v.* from Planning.RefineryUnitMonthDatas r
join Planning.RefineryUnitMonthDataValues v on r.Id = v.EntityId
    join(
        select EntityId, max(v.CreatedAt) CreatedAt from Planning.RefineryUnitMonthDatas r
        join Planning.RefineryUnitMonthDataValues v on r.Id = v.EntityId
        where RefineryUnitId = @refinery and Date / 100 = @date
        group by EntityId
    ) t on r.Id = t.EntityId
    where t.CreatedAt = v.CreatedAt

这是我的 linq:

 from s in db.RefineryUnitMonthDatas
 join v in db.RefineryUnitMonthDataValues on s.Id equals v.EntityId
 join r in (
      from r in db.RefineryUnitMonthDatas
      join v in db.RefineryUnitMonthDataValues on r.Id equals v.EntityId
      where r.RefineryUnitId == refinery  && r.Date / 100 == date
      group v by v.EntityId into g
      select new { g.Key, CreatedAt = g.Max(s => s.CreatedAt) }
 ) on s.Id equals r.Key
 where r.CreatedAt == v.CreatedAt
 select new { s, v }

这可以正常工作,但存在性能问题,并且最后一个 Where 子句未转换为 sql。它警告:

无法翻译 LINQ 表达式“where ([r].CreatedAt == [v].CreatedAt)”,将在本地计算

Core 2.2 是否支持子查询的 where 子句或我在某处犯了错误?

标签: c#sqllinqef-core-2.2

解决方案


似乎是(许多)EFC 2.2 查询翻译器错误/缺陷/缺点之一。在 EFC 3.1 中按预期工作。

从所有“查询模式”(他们称之为)中,我能找到的唯一一个工作是将谓词推入join子句,例如替换

) on s.Id equals r.Key
where r.CreatedAt == v.CreatedAt

有类似的东西

) on new { Key = s.Id, v.CreatedAt } equals new { r.Key, r.CreatedAt }

当然,解决方法仅适用于==可以转换为equi-join的比较。


推荐阅读