2009-07-06 306 views
4

我有一个奇怪的LINQ子查询问题。LINQ子查询返回null

由于数据结构如下:

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

所以,如果有是有位置“家”为编号1的父母孩子,我会得到孩子的“HasFoo”值,否则,我会得到错误的,这是我s是bool的“默认”值。

不过,如果我尝试编写查询,所以我的父对象列表,像这样:

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.

但是,我没有看到这个“空值”来自哪里。

回答

2

我不知道编译器是否推断HasHomeChildrenWithFoo是布尔,但实际上是铸造为一个可空布尔(因此弄乱了你的SingleOrDefault调用)。无论如何,我愿意打赌你可以通过在最终选择中将其转换为可空类型来修复它,然后可以在null时手动将其默认为false。它可能会使错误消失,但它是一种蛮力kludge。

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) 
       } 
+0

似乎很奇怪必须这样做,但它的工作原理!谢谢! :) – Jonas 2009-07-06 22:33:58