Skip to content
Advertisement

LINQ counts null as 1 – how to avoid that?

I am trying do replicate a simple COUNT / GROUP BY in LINQ. It works in SQL but my LINQ is not playing ball. I don’t want to count nulls but my LINQ statement does that for some reason.

Here is my SQL:

Which returns

Here is my LINQ – which counts null.

Which returns

What am I missing?

Advertisement

Answer

The type of DateCompleted on Request entity must be DateTime? or Nullable<DateTime> . This will tell Entity Framework that it should expect the column to be nullable and thus generate appropriate SQL. Right now, your code seems to compile, but that is because there is overload of DateTime‘s != opeartor and null being translated to DateTime type, which it cannot efficiently represent.

This will require change to the query :

And the predicate in count is unecessary.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement