【问题标题】:Sum of Count throw an exception, but SelectMany().Count() not throwSum of Count 抛出异常,但 SelectMany().Count() 不抛出
【发布时间】:2013-11-16 14:27:23
【问题描述】:
db.Projects.Select(x => new Statistic {
                          Posts = x.Members.Sum(m => m.Posts.Count())
                        })

为什么这段代码会抛出异常:

转换为值类型“System.Int32”失败,因为物化了 值为空。结果类型的泛型参数或查询 必须使用可空类型。

这段代码运行良好

db.Projects.Select(x => new Statistic {
                           Posts = x.Members.SelectMany(m => m.Posts).Count()
                        })

?

结构直观:

项目有很多成员。
会员有很多帖子。

public virtual ICollection<Post> Posts { get; set; }

编辑:最终工作代码

db.Projects.Select(x => new Statistic {
                          Posts = (int?)x.Members.Sum(m => m.Posts.Count()) ?? 0
                        })

【问题讨论】:

  • Posts 为空。尝试将 nullint 转换为 Sum() 失败。

标签: c# linq


【解决方案1】:

您的SumCount() 正在抛出一个空值。

允许Statistic 类中的Posts 可以为空,并将值转换为可以为空的整数。

db.Projects
    .Select(x => new Statistic
    {
        Posts = (int?)x.Members.Sum(m => (int?)m.Posts.Count())
    })

或者使用.Value 获取值。如果计数的总和仍然产生空值,.Value 方法仍然会抛出异常。

db.Projects
    .Select(x => new Statistic
    {
        Posts = x.Members.Sum(m => (int?)m.Posts.Count()).Value
    })

【讨论】:

  • 是的,非常感谢!此变体适用于Posts = (int?)x.Members.Sum(m =&gt; (int?)m.Posts.Count() ?? 0) ?? 0
  • 如果你能解释一下为什么会这样?
  • 为什么这样可以解决问题?在不知道数据的确切结构或内容的情况下,很难确定,但您的Count()Sum() 正在返回null。将这些转换为可空整数 int? 允许 Sum()Count() 为空的情况下处理所述空。
【解决方案2】:

这是因为Members 属性可以为空。您应该添加一个检查它是否为空,然后您的第一种方法会正常工作。

例如:

db.Projects.Select(x => new Statistic {
    Posts = x.Members==null? 0 :  x.Members.Sum(m => m.Posts.Count())
})

【讨论】:

  • 我认为成员不能为空,它应该是一个空集合
猜你喜欢
  • 1970-01-01
  • 2019-11-11
  • 2010-12-09
  • 2013-05-24
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 2020-09-24
  • 2012-01-24
相关资源
最近更新 更多