LINQ to SQL-where子句中的可为空类型
问题描述:
我有一个表,其中的列具有空值...当我尝试查询该列为NULL的记录时:
I have a table with a column that has null values... when I try to query for records where that column IS NULL:
此工作:
var list = from mt in db.MY_TABLE
where mt.PARENT_KEY == null
select new { mt.NAME };
这不是:
int? id = null;
var list = from mt in db.MY_TABLE
where mt.PARENT_KEY == id
select new { mt.NAME };
为什么?
答
经过更多的谷歌搜索后,我找到了答案:
after some more googling, I found the answer:
int? id = null;
var list = from mt in db.MY_TABLE
where object.Equals(mt.PARENT_KEY, id) //use object.Equals for nullable field
select new { mt.NAME };
此LINQ如下显示为SQL:
((mt.PARENT_KEY IS NULL) AND (@id IS NULL))
OR ((mt.PARENT_KEY IS NOT NULL) AND (@id IS NOT NULL) AND (mt.PARENT_KEY = @id))