本质上,我正在尝试通过 Linq 生成以下 SQL 查询:
SELECT *
FROM `CustomerMainTable` AS `t`
WHERE `t`.`CustomerMainTableId` IN (
SELECT MAX(`t0`.`CustomerMainTableId`)
FROM `CustomerMainTable` AS `t0`
GROUP BY `t0`.`CustomerMainTableCustomerId`
)
CustomerMainTableId
是自增id,CustomerMainTableCustomerId
是客户的唯一ID。
CustomerMainTableId
中可以有多个客户的交易条目,所以思路是通过分组和选择最大id来为每个客户选择最新的交易。
在实体框架核心 3.1 中,这是通过以下方式实现的:
var CustomerGroupQuery = _DB.CustomerMainTable.Where(p => _DB.CustomerMainTable
.GroupBy(l => l.CustomerMainTableCustomerId)
.Select(g => g.Max(c => c.CustomerMainTableId))
.Contains(p.CustomerMainTableId));
但是,相同的查询在 EF Core 6 或 7 中执行时会在 SQL 中产生错误的查询:
SELECT *
FROM `CustomerMainTable` AS `t`
WHERE EXISTS (
SELECT 1
FROM `CustomerMainTable` AS `t0`
GROUP BY `t0`.`CustomerMainTableCustomerId`
HAVING MAX(`t0`.`CustomerMainTableId`) = `t`.`CustomerMainTableId`)
有趣的是,如果我们像这样拆分 Linq 查询:
List<int> idlist = _DB.CustomerMainTable
.GroupBy(l => l.CustomerMainTableCustomerId)
.Select(g => g.Max(c => c.CustomerMainTableId)).ToList();
var CustomerGroupQuery = _DB.CustomerMainTable.Where(p => idlist.Contains(p.CustomerMainTableId));
它产生正确的查询 - 但需要返回一个整数列表..这不太理想。
有人知道这个问题的解决方法吗?
对于 EF Core 6 和 7,您可以使用其他技术获取组的最新记录:
var CustomerGroupQuery = _DB.CustomerMainTable
.GroupBy(l => l.CustomerMainTableCustomerId)
.Select(g => g.OrderByDescending(c => c.CustomerMainTableId).First());