2012-05-05 51 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; 
}