Handling null values in where clause using LINQ-to-SQL

Use

object.Equals()

.Net would take care of generating correct sql for null condition.

Example:

Say you have a street table with columns like Suffix and Prefix. Then following linq query doesn't work:

  string suffix = "ST";
  string prefix = null;

  var map = from s in Streets
            where s.Suffix==suffix || s.Prefix==prefix
            select s;

It would generate following sql:

SELECT [t0].[StreetId], [t0].[Prefix], [t0].[Suffix]
FROM [Street] AS [t0]
WHERE ([t0].[Suffix] = @p0) AND ([t0].[Prefix] = @p1)

we can clearly see it will not return any result.

Using object.Equals():

  string suffix = "ST";
  string prefix = null;

  var map = from s in Streets
  where object.Equals(s.Suffix, suffix) && object.Equals(s.Prefix,prefix)
  select s;

would generate sql:

SELECT [t0].[StreetId], [t0].[Prefix], [t0].[Suffix]
FROM [Street] AS [t0]
WHERE ([t0].[Suffix] IS NOT NULL) AND ([t0].[Suffix] = @p0) 
         AND ([t0].[Prefix] IS NULL)

Which is correct one.

(Little late, but wanted to expand the answer for the benefit of others)


try this:

where object.Equals(t.IdRole, access.IdRole)

Tags:

C#

Linq To Sql