如何在LINQ to SQL中检查空值

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

检查一下,如果 ParenCategoryID 等于 NULL,那么就做你想做的事情。 - vishiphone
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;
} 

object.Equals会被翻译成SQL吗?如果是,查询应该长什么样子? - Renatas M.
@Reniuz 是的,它会这样做,它将是:WHERE [t0].[ParenCategoryId] IS NULL - Magnus
@Reniuz 是的,而且它是由 Linq to Sql 进行优化的,具体取决于可空变量的值: http://www.brentlamborn.com/post/LINQ-to-SQL-Null-check-in-Where-Clause.aspx#id_0d234c8d-7ed4-4b1e-97ba-fcc38bb4d277 - Michael Buen

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接