0

In Linq or Linq to Sql to be more accurate: is there a difference between the == null and the IsNullOrEmpty in the below queries?

From a in context.SomeTable
where a.SomeId.Equals(SomeOtherId)
&& a.SomeOtherColumn == null
Select new .....

&

From a in context.SomeTable
where a.SomeId.Equals(SomeOtherId)
&& string.IsNullOrEmpty(a.SomeOtherColumn)
Select new .....
KeyboardFriendly
  • 1,788
  • 5
  • 30
  • 41
  • Well I don't know linq but SQl Server would consider empty string and NUll as two differnt things (this needing two differnt commands) while Oracle may not. So I would bet for some databases it makes a differnce and in others it does not. – HLGEM Sep 17 '13 at 21:00

5 Answers5

6

You cannot do String.IsNullOrEmpty in Linq-SQL:

Method 'Boolean IsNullOrEmpty(System.String)' has no supported translation to SQL.

If you need that, I guess you will have to have both the null and empty check in your where clause:

&& (a.SomeOtherColumn == null || a.SomeOtherColumn == "")

Which will translate to a null and empty check in SQL.

Looking at the other answers, using .Length == 0, will generate SQL to check the length of the varchar column, which may be less efficient than checking if a varchar is equal to ''.

EDIT: Here's a Stack Overflow answer on Length versus Empty check for SQL. It seems I guessed right.

Community
  • 1
  • 1
DaveShaw
  • 50,828
  • 16
  • 110
  • 139
1

The string.IsNullOrEmpty also applies to an empty string like ""

Jeroen van Langen
  • 19,966
  • 3
  • 36
  • 54
1

The most obvious difference is in the name. IsNullOrEmpty also checks whether the string is empty. It would be equivalent to:

from a in context.SomeTable
where a.SomeId.Equals(SomeOtherId)
&& (a.SomeOtherColumn == null || a.SomeOtherColumn.Length == 0)
...

Or

from a in context.SomeTable
where a.SomeId.Equals(SomeOtherId)
&& (a.SomeOtherColumn == null || a.SomeOtherColumn == "")
...
p.s.w.g
  • 141,205
  • 29
  • 278
  • 318
1

While other answers have stated the obvious fact that .IsNullOrEmpty() checks for empty strings, it's also important to note that the comparison

where a.SomeOtherColumn == someNullVariable

will never return any values in LINQ-to-SQL, due to using SQL null-comparisons rather than C# null-comparisons. This is actually a bug in LINQ-to-SQL.

Community
  • 1
  • 1
BlueRaja - Danny Pflughoeft
  • 80,074
  • 30
  • 187
  • 269
0

IsNullOrEmpty is equal to

s == null || s.Length == 0;

Where s is instance of string

Sriram Sakthivel
  • 69,953
  • 7
  • 104
  • 182