运行以下 EF Core 查询:
var groupData = await _dbContext.Groups.AsNoTracking()
.Where(g => g.Id == groupId)
.Select(g => new
{
/* ...some other fields are queried here... */
ActiveLab = g.ActiveLabs.FirstOrDefault(al => al.LabId == labId)
})
.FirstAsync(cancellationToken);
导致此错误:
MySqlException: You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'(PARTITION BY `l`.`GroupId` ORDER BY `l`.`GroupId`, `l`.`LabId`) AS `row`'
at line 6
检查生成的 SQL 会导致 EF 出于某种原因插入了一条PARTITION
指令:
SELECT `g`.`Name`, `t0`.`GroupId`, `t0`.`LabId`, `t0`.`StartTime`
FROM `Groups` AS `g`
LEFT JOIN (
SELECT `t`.`GroupId`, `t`.`LabId`, `t`.`StartTime`
FROM (
SELECT `l`.`GroupId`, `l`.`LabId`, `l`.`StartTime`, ROW_NUMBER() OVER(PARTITION BY `l`.`GroupId` ORDER BY `l`.`GroupId`, `l`.`LabId`) AS `row`
FROM `ActiveLabs` AS `l`
WHERE `l`.`LabId` = @__labId_1
) AS `t`
WHERE `t`.`row` <= 1
) AS `t0` ON `g`.`Id` = `t0`.`GroupId`
WHERE `g`.`Id` = @__groupId_0
LIMIT 1
我宁愿期待这样的查询:
SELECT `g`.`Name`, `l`.`GroupId`, `l`.`LabId`, `l`.`StartTime`
FROM `Groups` AS `g`
LEFT JOIN `ActiveLabs` AS `l`
ON `l`.`GroupId` = `g`.`Id`
WHERE `l`.`LabId` = @__labId_1 AND `g`.`Id` = @__groupId_0
LIMIT 1
JOIN
当一个简单的 onActiveLabs
就足够时,为什么 EF 会生成如此复杂的查询?
我正在使用 EF Core 3.1.2、Pomelo MySQL 3.1.1 和 MySQL 5.7.14 进行测试。
我的数据库如下所示: 我有两个表Groups
+----+--------+
| Id | Name |
+----+--------+
| 1 | Group1 |
| 2 | Group2 |
+----+--------+
和ActiveLabs
+---------+-------+----------------------------+
| GroupId | LabId | StartTime |
+---------+-------+----------------------------+
| 1 | 1 | 2020-03-01 00:00:00.000000 |
| 2 | 1 | 2020-03-01 00:00:00.000000 |
| 1 | 2 | 2020-03-08 00:00:00.000000 |
+---------+-------+----------------------------+
后者表示多对多关系,它跟踪哪个实验室对哪个组处于活动状态。因此,一个Group
对象有一个导航属性ActiveLabs
,它指向该组的活动实验室。类/表结构和外键是正确的,并且在所有用例中都能正常工作。
编辑:
看起来PARTITION
MySQL 5.7.14 根本不支持(Pomelo 的 GitHub 存储库上的相关问题)。升级到 MySQL 8.0 消除了错误消息,查询现在可以工作;但是,我仍然不明白为什么 EF 会生成PARTITION
(window function) 语句。