In the following Linq query, the generated SQL ignores the c.val != null check in Count()
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}
it is translated to
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)
whereas when written the following only
t.Count(c => c.ID != null && t.No > 10)
it is translated to
SELECT COUNT(*) AS [value]
FROM [t] AS [t0]
WHERE ([t0].[ID] IS NOT NULL) AND ([t0].[No] > @p0)
Here it is not skipping the c.ID != null check. Why is this behavior occurring? Are there any restrictions on the use of Count inside a where clause?
It is because of optimalisation. In sql is null=null false, this explains why you do not need the extra is null check in your first expression (smart rewrite in Linq). The transaltion of the second expression is not with a == so different optimalization are used. In this case the parser did no see that ([t0].[ID] IS NOT NULL) does not add any value in de sql expression.