LINQ to SQL FAQ – NULLs

Beware of the NULL

Null values are always something to be wary of in SQL, and LINQ to SQL is no different.

For example, given following expression on the Customers table in Northwind returns two rows:

var qry = from c in Customers where c.Country=="UK" && c.Fax == null select c;

However this query returns no rows!

string fax = null;
var qry = from c in Customers where c.Country=="UK"
   
&& c.Fax == fax select c;

Looking at the generated SQL (try LINQpad), the reason is that in SQL the first query has the filter

([t0].[Fax] IS NULL)

and the second query uses a parameter:

([t0].[Fax] = @p1)

In C# (and VB) you can say null == null, but in SQL NULL != anything-whatsoever-including-null

See http://blogs.msdn.com/dinesh.kulkarni/archive/2006/07/16/667968.aspx

 Workaround

There is a way to compensate for this I spotted in the sample queries with LINQPAD: using object.Equals(p1, p2) will correctly emit the correct SQL :

string fax = null;
var qry = from c in Customers where c.Country=="UK"
   
&& object.Equals (c.Fax, fax) select c;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s