Linq subquery returning null

I have an odd linq subquery problem.

Given the following data structure:

  Parents children
 ------- --------
 Id id
                    ParentId
                    Location
                    Hasfoo 

(obviously this is not a real structure, but close enough for this example)

I can run this query and get the 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(); 

So, if there is a child that has β€œHome” for parent ID 1, I get this β€œHasFoo” value for the child, otherwise I will get false, which is the default value for BOOL.

However, if I try to write a query, so I have a list of parent objects, for example:

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

I get the following error when iterating through a list:

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

I do not see where this "zero" value comes from.

+4
source share
1 answer

Interestingly, the compiler displays HasHomeChildrenWithFoo as bool, but then actually throws it into a nullable bool (thus messing up your SingleOrDefault call). Anyway, I would bet you can fix this by casting to a type with a null type in this final selection, which you can manually use by default to false when null. This will probably lead to the fact that the error disappears, but this is a kind of accumulation of brute force.

 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) } 
+2
source

All Articles