What is the best way to deal with nullable string columns in LinqToSql?
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 != "[Nul开发者_开发知识库ls]" ? 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.Equals
that will make LINQ handle null appropriately on the generated SQL query
var result = dataContext.MyTable
.Where(x => String.Equals(x.MyColumn, filter))
.ToList();
Edit:
If you use ==
LINQ will generate the query for the general case WHERE [column] = @parameter
but on SQL NULL does not match NULL, the proper way to test for NULL is [column] IS NULL
.
With String.Equals
LINQ 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
WHERE ([column] IS NOT NULL) AND ([column] = @parameter)
and if it is null
WHERE [column] IS NULL
精彩评论