如何在 LINQ to SQL 中检查空值
本文关键字:检查 空值 SQL to LINQ | 更新日期: 2023-09-27 18:33:25
我正在尝试使用以下linq到sql查询来获取结果。但如果父类别 ID 作为空传递,则它不起作用
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 代替父类别 ID 则以下工作
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;
}
您可以使用
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;
}
您可以尝试以下操作
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;
}