Nulls in Linq

Note to self: I know you got a lot going on (new babies, plague of new APIs etc…) but please remember that in the where clause of Linq To Sql there is no “IS NULL” without using the proper syntax. If you want the resulting query to be “where column IS NULL” you have to use the word “null” in your linq statement.

So rather than this…

string LastName = null;
var query = from ctx.People.Where(x => x.LName == LastName )

… you gotta say the following if you are unsure of the value of your variable…

string LastName = null;
var query = from ctx.People.Where(x => (x.LName == LastName) || (x.LName == null && LastName == null) )

This second one will result is a query being sent that uses Sql like “where LName IS NULL”  rather than “where LName = NULL” (which fails in SQL) …

Advertisements

About this entry