LINQ 函数中可空类型的问题
Parent_ObjectiveID
和 identity
是 int?
数据类型。在我的程序中应该返回一个对象,但它给出了一个错误:序列不包含元素
。
int? identity = null;
Objective currentObjective = (from p in cd.Objective
where p.Parent_ObjectiveID == identity
select p).Single();
虽然,如果我将身份变量替换为空。它有效,但我不明白。
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();
}
但我不太喜欢它。
Parent_ObjectiveID
and identity
are int?
datatype. In my program should return an object, but it gives an error: Sequence contains no elements
.
int? identity = null;
Objective currentObjective = (from p in cd.Objective
where p.Parent_ObjectiveID == identity
select p).Single();
Although, if I replace identity variable to null. It works, but I don't understand.
currentObjective = (from p in cd.Objective
where p.Parent_ObjectiveID == null
select p).Single();
What's happening?
UPDATE 1:
I have done this:
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();
}
But I don't really like it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
LINQ 似乎不支持 where 子句中的这种情况。
这个问题是关于同样的问题。另请参阅此线程< /a>.
您可以尝试:
编辑:如果这不起作用,请尝试与 object.Equals 进行比较:
LINQ does not seem to support this case in the where clause.
This question is about the same problem. Also see this thread.
You could try:
EDIT: If this does not work, try to compare with object.Equals:
我在 LINQ to SQL Null 找到了一篇文章检查Where子句解释了这个问题。看起来您可以使用
object.Equals
代替:I found an article at LINQ to SQL Null check in Where Clause that explains this problem. It looks like you can use
object.Equals
instead:将被编译为“select * from Objective where Parent_ObjectiveID == @identity”。并且,
将被编译为“从 Parent_ObjectiveID 为 null 的目标中选择 *”。
当您的 @identity 为 null 时,子句“where Parent_ObjectiveID == null”将始终返回“false”。
will be compiled to 'select * from objective where Parent_ObjectiveID == @identity'. And,
will be compiled to 'select * from objective where Parent_ObjectiveID is null'.
The clause 'where Parent_ObjectiveID == null' will always return 'false' when your @identity is null.