5

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.

Malachi
  • 3,205
  • 4
  • 29
  • 46
oscar.fimbres
  • 1,145
  • 1
  • 13
  • 24

3 Answers3

1

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();
Community
  • 1
  • 1
magnattic
  • 12,638
  • 13
  • 62
  • 115
  • The first code should work, although it returns a (int?)null and to work it would be just null. Maybe I should work with Where claussule and expressions to eliminate that super if – oscar.fimbres Aug 16 '11 at 23:20
0

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
Jacob
  • 77,566
  • 24
  • 149
  • 228
0
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.