如何检查linq中的空值为sql

时间:2012-05-05 09:17:38

标签: c# linq-to-sql

我正在尝试使用以下linq到sql查询来获取结果。但是如果parentCategoryId传递为null

,则它不起作用
 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;
    }   

但如果null直接用于​​替代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;
    }

2 个答案:

答案 0 :(得分: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;
} 

答案 1 :(得分: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;
}