5

我正在尝试使用以下 linq to 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;
    }
4

2 回答 2

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;
} 
于 2012-05-05T09:33:35.807 回答
0

You can try the following

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;
}  
于 2012-05-05T09:49:01.723 回答