gpt4 book ai didi

c# - Linq 计数(条件)未按预期工作

转载 作者:太空宇宙 更新时间:2023-11-03 16:25:46 24 4
gpt4 key购买 nike

在下面的 Linq 查询中,生成的 SQL 忽略了 Count() 中的 c.val != null 检查

from t1 in table1
join t2 in table2 on t1.col1 equals t2.col1
where t1.col1 = 123 && t3.Count(c => c.val != null && c.col1 == t1.col1) == 0
select new {t1.col1, t2.col2, t1.col2}

翻译成

SELECT [t0].[col1], [t1].[col2], [t0].[col2]
FROM [t1] AS [t0]
INNER JOIN [t2] AS [t1] ON [t0].[col1] = [t1].[col1]
WHERE ([t0].[col1] = @p0) AND (((
SELECT COUNT(*)
FROM [t3] AS [t2]
WHERE [t2].[col1] = [t0].[col1]
)) = @p1)

而当只写以下内容时

t.Count(c => c.ID != null && t.No > 10)

翻译成

SELECT COUNT(*) AS [value]
FROM [t] AS [t0]
WHERE ([t0].[ID] IS NOT NULL) AND ([t0].[No] > @p0)

这里没有跳过 c.ID != null 检查。为什么会出现这种行为?在 where 子句中使用 Count 有什么限制吗?

最佳答案

这是因为优化。在 sql 中是 null=null false,这解释了为什么您不需要在第一个表达式中进行额外的 is null 检查(Linq 中的智能重写)。第二个表达式的转换没有使用 ==,因此使用了不同的优化。在这种情况下,解析器没有看到 ([t0].[ID] IS NOT NULL) 没有在 de sql 表达式中添加任何值。

关于c# - Linq 计数(条件)未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12619864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com