1

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,798
  • 5
  • 32
  • 42
  • 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

7

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
  • 52,123
  • 16
  • 112
  • 141
1

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

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
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
  • 146,324
  • 30
  • 291
  • 331
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
  • 84,206
  • 33
  • 197
  • 283
0

IsNullOrEmpty is equal to

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

Where s is instance of string

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189