linq子查询返回null

时间:2009-07-06 22:08:37

标签: linq linq-to-sql

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

鉴于以下数据结构:

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

(显然这不是真正的结构,但它足够接近这个例子)

我可以运行此查询并获得所需的结果:

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();

因此,如果有一个孩子的Id为1的Parent的位置为“Home”,我将获得该Child的“HasFoo”值,否则,我将得到false,这是一个“默认”值布尔。

但是,如果我尝试编写查询,那么我有一个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()
                 }

迭代列表时出现以下错误:

The null value cannot be assigned to a member with type System.Boolean which is a non-nullable value type.

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

1 个答案:

答案 0 :(得分:3)

我想知道编译器是否推断HasHomeChildrenWithFoo是bool,但实际上是否会转换为可以为空的bool(从而弄乱了你的SingleOrDefault调用)。无论如何,我愿意打赌你可以在最终选择中使用强制转换为可归类型来修复它,然后你可以在null时手动默认为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)
                 }
相关问题