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.
但是,我没有看到这个“空值”来自哪里。
似乎很奇怪必须这样做,但它的工作原理!谢谢! :) – Jonas 2009-07-06 22:33:58