Assume you have a table with a nullable varchar column. When you try to filter the table, you would use (pFilter is parameter):
var filter = pFilter;
var dataContext = new DBDataContext();
var result = dataContext.MyTable.Where(x=>x.MyColumn == filter).ToList();
Now, what if there is a keyword that means “All Nulls”. The code would look like:
var filter = pFilter != "[Nulls]" ? pFilter : null;
var dataContext = new DBDataContext();
var result = dataContext.MyTable.Where(x=>x.MyColumn == filter).ToList();
But this doesn’t work. Apparently, a String with value of null is… not null?
However, what do work is this code:
var filter = pFilter != "[Nulls]" ? pFilter : null;
var dataContext = new DBDataContext();
var result = dataContext.MyTable.Where(x=>x.MyColumn == filter || (filter == null && x.MyColumn == null)).ToList();
The workaround did not convinced me, that’s why my question is: What is the best way to deal with nullable string columns in LinqToSql?
Use
String.Equalsthat will make LINQ handle null appropriately on the generated SQL queryEdit:
If you use
==LINQ will generate the query for the general caseWHERE [column] = @parameterbut on SQL NULL does not match NULL, the proper way to test for NULL is[column] IS NULL.With
String.EqualsLINQ has enough information to translate the method to the appropiate sentence in each case, what means:if you pass a non-null string it will be
and if it is null