如何检查linq中的空值为sql

Sur*_*rya 5 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;
    }   
Run Code Online (Sandbox Code Playgroud)

但是如果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;
    }
Run Code Online (Sandbox Code Playgroud)

Mag*_*nus 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;
} 
Run Code Online (Sandbox Code Playgroud)