LINQ函数中可空类型的问题

osc*_*res 5 c# linq linq-to-objects nullable linq-to-sql

Parent_ObjectiveID并且identityint?数据类型.在我的程序中应该返回一个对象,但它给出了一个错误:Sequence contains no elements.

int? identity = null;

Objective currentObjective = (from p in cd.Objective
                              where p.Parent_ObjectiveID == identity
                              select p).Single();
Run Code Online (Sandbox Code Playgroud)

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

currentObjective = (from p in cd.Objective
                    where p.Parent_ObjectiveID == null
                    select p).Single();
Run Code Online (Sandbox Code Playgroud)

发生了什么?

更新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();
}
Run Code Online (Sandbox Code Playgroud)

但我真的不喜欢它.

mag*_*tic 1

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

这个问题是关于同样的问题。另请参阅此线程

你可以尝试:

Objective currentObjective = (from p in cd.Objective
                                  where p.Parent_ObjectiveID == (identity ?? null)
                                  select p).Single();
Run Code Online (Sandbox Code Playgroud)

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

Objective currentObjective = (from p in cd.Objective
                                  where object.Equals(p.Parent_ObjectiveID, identity)
                                  select p).Single();
Run Code Online (Sandbox Code Playgroud)