【发布时间】:2021-12-29 05:02:17
【问题描述】:
我有一个这样的 Linq2Sql 查询:
Parent.Include(p => p.Children)
.Where(p => p.Children.Any(c => c.SomeNullableDateTime == null)
&& p.Children
.Where(c => c.SomeNullableDateTime == null)
.OrderBy(c => c.SomeInteger)
.First()
.SomeOtherNullableDateTime != null
)
.Select(p => p.Children
.Where(c => c.SomeNullableDateTime == null)
.OrderBy(c => c.SomeInteger)
.First()
.SomeOtherNullableDateTime)
.ToList();
在从 EF 核心 5 移动到 EF 核心 6 之前,这工作正常。对于 EF 核心 6,结果列表包含一些空值(不应该是这种情况,因为 where 条件要求不为空)。 EF core 6 中是否有一些我不知道的重大更改/限制,或者这只是一个错误?
更新:这是输出的摘录
更新 2:这是生成的 SQL 语句
SELECT(
SELECT TOP(1)[p1].[SomeOtherNullableDateTime]
FROM[Children] AS[p1]
WHERE([p].[Id] = [p1].[ParentId]) AND[p1].[SomeNullableDateTime] IS NULL
ORDER BY[p1].[SomeInteger])
FROM[Parent] AS[p]
WHERE EXISTS(
SELECT 1
FROM[Children] AS [c]
WHERE ([p].[Id] = [c].[ParentId]) AND[c].[SomeNullableDateTime] IS NULL) AND EXISTS(
SELECT 1
FROM[Children] AS [c0]
WHERE ([p].[Id] = [c0].[ParentId]) AND[c0].[SomeNullableDateTime] IS NULL)
GO
所以看起来问题是 SomeOtherNullableDateTime(应该不为空)甚至没有包含在生成的 SQL 的 where 子句中。
更新 3:这是 SQL EF 核心 5(正确)生成
SELECT (
SELECT TOP(1) [c].[SomeOtherNullableDateTime]
FROM [Children] AS [c]
WHERE ([p].[Id] = [c].[ParentId]) AND [c].[SomeNullableDateTime] IS NULL
ORDER BY [c].[SomeInteger])
FROM [Parent] AS [p]
WHERE EXISTS (
SELECT 1
FROM [Children] AS [c0]
WHERE ([p].[Id] = [c0].[ParentId]) AND [c0].[SomeNullableDateTime] IS NULL) AND (
SELECT TOP(1) [c1].[SomeOtherNullableDateTime]
FROM [Children] AS [c1]
WHERE ([p].[Id] = [c1].[ParentId]) AND [c1].[SomeNullableDateTime] IS NULL
ORDER BY [c1].[SomeInteger]) IS NOT NULL
GO
【问题讨论】:
-
生成的SQL语句是什么?
-
@StefanGolubović:我已将生成的 sql 语句添加到问题中
-
我觉得奇怪的是你没有在声明的末尾加上 .First。
-
为什么是
Include,然后是Select?这两件事不能很好地结合在一起(很可能Include被忽略了)。我只想Select+Where。 -
@IvanStoev:我只是想弄清楚你想说什么:-D
标签: entity-framework-core ef-core-6.0