2012-05-05 16 views
5

Sto cercando di usare la seguente query da linq a sql per ottenere il risultato. Ma non è così, se le opere parentCategoryId passato come nullacome controllare il valore nullo in linq a sql

public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId) 
    { 
     var categories = from c in source where c.ParenCategoryId == parentCategoryId select c; 
     return categories; 
    } 

ma seguenti opere se nulla utilizzate direttamente al posto di parentCategoryId

public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId) 
    { 
     var categories = from c in source where c.ParenCategoryId == null select c; 
     return categories; 
    } 
+0

se (ParenCategoryID isEqualTo: NULL) poi fare quello che vuoi. – vishiphone

risposta

8

Si può usare object.Equals, si abbinerà a null valori anche.

public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId) 
{ 
    var categories = from c in source 
        where object.Equals(c.ParenCategoryId, parentCategoryId) 
        select c; 
    return categories; 
} 
+0

oggetto. Gli importi saranno tradotti in sql? se sì, come sarà la query? – Reniuz

+0

@Reniuz Sì, sarà: 'WHERE [t0]. [ParenCategoryId] IS NULL' – Magnus

+0

@Reniuz yes, ed è ottimizzato da Linq a Sql in base al valore della variabile nullable: http: //www.brentlamborn .com/post/LINQ-to-SQL-Null-check-in-Where-Clause.aspx # id_0d234c8d-7ed4-4b1e-97ba-fcc38bb4d277 –

0

È possibile provare il seguente controllo

public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId) 
{ 
    var categories = from c in source 
        where (parentCategoryId != null? c.ParenCategoryId == parentCategoryId : c.ParenCategoryId == null) 
        select c; 
    return categories; 
} 
Problemi correlati