linq 子查询返回空值

标签 linq linq-to-sql

我有一个奇怪的 linq 子查询问题。

给定以下数据结构:

Parents            Children
-------            --------
Id                 Id
                   ParentId
                   Location
                   HasFoo

(obviously this is not the real structure, but it's close enough for this example)

I'm able to run this query and get a desired result:

bool b = (from p in Parents
          from c in Children
          where p.Id == 1 && c.ParentId == p.Id && c.Location == "Home"
          select c.HasFoo).SingleOrDefault();

因此,如果有一个 child 的位置为 Id 1 的父级的“家”,我将获得该 child 的“HasFoo”值,否则,我将获得 false,这是 bool 的“默认”值。

但是,如果我尝试编写查询,则我有一个 Parent 对象列表,如下所示:
var parentList = from p in Parents
                 select new ParentObject
                 {
                   ParentId = p.ParentId,
                   HasHomeChildren = p.Children.Count(c => c.Location == "Home") > 0,
                   HasHomeChildrenWithFoo = (from c in p.Children where c.Location == "Home" select c.HasFoo).SingleOrDefault()
                 }

遍历列表时出现以下错误:

不能将空值分配给 System.Boolean 类型的成员,该成员是不可为空的值类型。

但是,我看不到这个“空”值的来源。

最佳答案

我想知道编译器是否将 HasHomeChildrenWithFoo 推断为 bool,但实际上转换为可空的 bool(从而弄乱了您的 SingleOrDefault 调用)。无论如何,我愿意打赌您可以在最终选择中通过强制转换为可空类型来修复它,然后您可以在为空时手动默认为 false。它可能会使错误消失,但这是一种蛮力的混搭。

var parentList = from p in Parents
                 select new ParentObject
                 {
                   ParentId = p.ParentId,
                   HasHomeChildren = p.Children.Any(c => c.Location == "Home"),
                   HasHomeChildrenWithFoo = (from c in p.Children where c.Location == "Home" select (bool?)c.HasFoo) ?? false)
                 }

关于linq 子查询返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1089427/

相关文章:

linq - 另一个排列词难题…与Linq一起吗?

linq-to-sql - 如何在 Linq to SQL 导航属性生成的查询中使用左连接而不是内连接

c# - 我如何使用 linq 将字符串日期时间解析为实际日期时间?

c# - 尽管使用 *include* 仍出现 ObjectDisposeException

c# - LINQ to Entities 等效于 sql "TOP(n) WITH TIES"

LINQ 按结果属性拆分和分组

c# - 彩票入场方式

c# - 接受返回 null 的方法 - C# .NET MVC

Linq to SQL怎么办 "where [column] in (list of values)"

c# - LINQ to SQL 问题