Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with nullable types in a LINQ Function

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.

like image 813
oscar.fimbres Avatar asked Nov 13 '22 18:11

oscar.fimbres


1 Answers

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();
like image 154
magnattic Avatar answered Dec 10 '22 05:12

magnattic