Reputation: 1147
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.
Upvotes: 5
Views: 636
Reputation:
from p in cd.Objective
where p.Parent_ObjectiveID == identity
select p
will be compiled to 'select * from objective where Parent_ObjectiveID == @identity'. And,
from p in cd.Objective
where p.Parent_ObjectiveID == null
select p
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.
Upvotes: 0
Reputation: 13028
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:
Objective currentObjective = (from p in cd.Objective
where p.Parent_ObjectiveID == (identity ?? null)
select p).Single();
EDIT: If this does not work, try to compare with object.Equals:
Objective currentObjective = (from p in cd.Objective
where object.Equals(p.Parent_ObjectiveID, identity)
select p).Single();
Upvotes: 1
Reputation: 78900
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:
from p in cd.Objective
where object.Equals(p.Parent_ObjectiveID, identity)
select p
Upvotes: 0