2012-05-05 41 views
5

我想要使用以下LINQ到SQL查詢來獲得結果。但它並不適用於如果parentCategoryId爲空如何檢查LINQ到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; 
    } 

通過,但下面的作品,如果空直接用於地方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

檢查(ParenCategoryID isEqualTo:NULL),那麼你想要做什麼。 – vishiphone

回答

8

您可以使用object.Equals,它將匹配null值也。

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

object.Equals將被轉換爲sql?如果是,如何查詢將看起來像? – Reniuz

+0

@Reniuz是的,它會:'WHERE [t0]。[ParenCategoryId] IS NULL' – Magnus

+0

@Reniuz是的,它根據可變的變量的值由Linq to Sql優化:http://www.brentlamborn .com/post/LINQ-to-SQL -Null-check-in-Where-Clause.aspx#id_0d234c8d-7ed4-4b1e-97ba-fcc38bb4d277 –

0

你可以嘗試以下

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