【问题标题】:LINQ Subquery Where Clause could not be translated无法翻译 LINQ 子查询 Where 子句
【发布时间】:2023-04-02 02:45:01
【问题描述】:

我在 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# sql linq ef-core-2.2


    【解决方案1】:

    似乎是(许多)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

    【讨论】:

    • 感谢回复,我升级到Core 3.1并检查了,在EFC 3.1中Where caluse仍然不起作用,但是在EFC 3.1中修复了equi-join方法
    • 嗨@Zatkhahi,它完全按照我解释的方式对我有用。当然,我已经使用我认为类似的查询进行了测试,因为您没有包含模型类。不幸的是,在 EFC 版本之间使用 EF Core 查询转换实际上是一种试错方法,并且必须在每个新版本中重新测试(它们修复了一些东西,但破坏了其他东西等)。请注意,在 3.x 中,许多在 2.x 中是由客户端评估导致的低效率的事情现在是运行时异常。
    猜你喜欢
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多