LINQ函数中可空类型的问题

时间:2011-08-16 22:13:03

标签: c# linq linq-to-sql linq-to-objects nullable

Parent_ObjectiveIDidentityint?数据类型。在我的程序中应返回一个对象,但它会出错:Sequence contains no elements

int? identity = null;

Objective currentObjective = (from p in cd.Objective
                              where p.Parent_ObjectiveID == identity
                              select p).Single();

虽然,如果我将identity变量替换为null。它有效,但我不明白。

currentObjective = (from p in cd.Objective
                    where p.Parent_ObjectiveID == null
                    select p).Single();

发生了什么事?

更新1:

我做到了:

if (identity == null)
{
     currentObjective = (from p in cd.Objective
                         where p.Parent_ObjectiveID == null
                         select p).Single();
}
else
{
     currentObjective = (from p in cd.Objective
                         where p.Parent_ObjectiveID == identity
                         select p).Single();
}

但我真的不喜欢它。

3 个答案:

答案 0 :(得分:1)

LINQ似乎不支持where子句中的这种情况。

This question也存在同样的问题。另请参阅this thread

你可以尝试:

Objective currentObjective = (from p in cd.Objective
                                  where p.Parent_ObjectiveID == (identity ?? null)
                                  select p).Single();

编辑:如果这不起作用,请尝试与object.Equals进行比较:

Objective currentObjective = (from p in cd.Objective
                                  where object.Equals(p.Parent_ObjectiveID, identity)
                                  select p).Single();

答案 1 :(得分:0)

我在LINQ to SQL Null check in Where Clause找到了一篇解释此问题的文章。看起来您可以使用object.Equals代替:

from p in cd.Objective
where object.Equals(p.Parent_ObjectiveID, identity)
select p

答案 2 :(得分:0)

from p in cd.Objective
where p.Parent_ObjectiveID == identity
select p

将编译为'select * from objective where Parent_ObjectiveID == @identity '。而且,

from p in cd.Objective
where p.Parent_ObjectiveID == null
select p

将被编译为'select * from objective where Parent_ObjectiveID 为null '。

当您的@identity为空时,子句'where Parent_ObjectiveID == null'将始终返回'false'。