2011-08-16 13 views
5

Parent_ObjectiveID y identity son int? tipo de datos. En mi programa debería devolver un objeto, pero da un error: Sequence contains no elements.Problemas con tipos anulables en una función LINQ

int? identity = null; 

Objective currentObjective = (from p in cd.Objective 
           where p.Parent_ObjectiveID == identity 
           select p).Single(); 

Aunque, si reemplazo la variable de identidad por nulo. Funciona, pero no entiendo.

currentObjective = (from p in cd.Objective 
        where p.Parent_ObjectiveID == null 
        select p).Single(); 

¿Qué está pasando?

ACTUALIZACIÓN 1:

he hecho esto:

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(); 
} 

Pero en realidad no me gusta.

+0

¿Estás hablando de Linq-To-Sql o Linq-To-Objects? Acabo de probar esto con Linq-To-Objects, y funciona para mí. (.NET 4.0) – magnattic

+0

@atticae Linq a SQL –

+0

¿Por qué lo etiquetó con 'linq-to-objects' luego? ;) – magnattic

Respuesta

1

LINQ no parece apoyar este caso en la cláusula where.

This question es aproximadamente el mismo problema. También vea this thread.

Usted podría intentar:

Objective currentObjective = (from p in cd.Objective 
            where p.Parent_ObjectiveID == (identity ?? null) 
            select p).Single(); 

EDIT: Si esto no funciona, trate de comparar con Object.equals:

Objective currentObjective = (from p in cd.Objective 
            where object.Equals(p.Parent_ObjectiveID, identity) 
            select p).Single(); 
+0

que no entiendo todavía –

+0

ver mi edición, esto debería funcionar – magnattic

+0

El primer código debería funcionar, aunque se devuelve un (int?) nula y trabajar sería simplemente nula. Tal vez debería trabajar con Where claussule y expresiones para eliminar ese super si –

0

he encontrado un artículo en LINQ to SQL Null check in Where Clause que explica este problema. Parece que se puede utilizar en lugar object.Equals:

from p in cd.Objective 
where object.Equals(p.Parent_ObjectiveID, identity) 
select p 
+0

No funcionó Jacob –

0
from p in cd.Objective 
where p.Parent_ObjectiveID == identity 
select p 

se compilará a 'seleccionar * de objetivo donde Parent_ObjectiveID == @identity'. Y,

from p in cd.Objective 
where p.Parent_ObjectiveID == null 
select p 

se compilará a 'seleccionar * de objetivo donde Parent_ObjectiveID es nulo'.

La cláusula 'donde Parent_ObjectiveID == null' con Gusto 'falso' cuando su @identity es nulo.

Cuestiones relacionadas