【问题标题】:linq subquery returning nulllinq 子查询返回 null
【发布时间】:2009-07-06 22:08:36
【问题描述】:

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

给定以下数据结构:

父母子女
-------- --------
身份证号码
                   父 ID
                   地点
                   有福

(显然这不是真正的结构,但对于这个例子来说已经足够接近了)

我能够运行此查询并获得所需的结果:

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,我将获得该孩子的“HasFoo”值,否则,我将获得 false,这是一个“默认”值布尔值。

但是,如果我尝试编写查询,那么我有一个父对象列表,如下所示:

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

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

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

但是,我看不出这个“null”值是从哪里来的。

【问题讨论】:

    标签: linq linq-to-sql


    【解决方案1】:

    我想知道编译器是否将 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)
                     }
    

    【讨论】:

    • 是的,我知道这很奇怪 :)。很高兴它奏效了。不久前,我偶然发现了一个类似问题的技巧(stackoverflow.com/questions/341264)。如果您有兴趣,我在此处链接的文章可能会提供更多信息:interact-sw.co.uk/iangblog/2007/09/10/linq-aggregates
    • 更正确的查询将使用.Any(c => c.Location == "Home") 而不是.Count(c => c.Location == "Home") > 0,这将转换为sql EXISTS 而不是COUNT()
    • 我喜欢@TsahiAsher。好点子。我需要养成这种习惯,因为我倾向于通过简单的反射走 Count 路线,而 Any 可以更好地表达意图并避免额外(尽管轻微)的处理负担。
    猜你喜欢
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多