from i in Db.Items
select new VotedItem
{
ItemId = i.ItemId,
Points = (from v in Db.Votes
where b.ItemId == v.ItemId
select v.Points).Sum()
}
我收到了这个查询,但是如果没有发现投票,则查询会失败:
The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.
我认为它是因为 sum 返回一个 int 而不是一个可为 null 的 int,给 sum 一个 int?因为输入只给出相同的错误,可能导致 sum 只适用于整数。
有什么好的解决方法吗?
您想要使用 Sum 的可为 null 形式,因此请尝试将您的值转换为可为 null:
from i in Db.Items
select new VotedItem
{
ItemId = i.ItemId,
Points = (from v in Db.Votes
where b.ItemId == v.ItemId
select v.Points).Sum(r => (decimal?) r.Points)
}
这里更详细地讨论您的问题:
http://weblogs.asp.net/zeeshanhirani/archive/2008/07/15/applying-aggregates-to-empty-collections-causes-exception-in-linq-to-sql.aspx http://weblogs.asp.net/zeeshanhirani/archive/2008/07/15/applying-aggregates-to-empty-collections-causes-exception-in-linq-to-sql.aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)