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()
}
我收到了这个查询,但是如果没有发现异常投票,它就会失败:
I got this query, however it fails if no votes are found with exception:
The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.
我假设它是因为 sum 返回一个 int 而不是一个可为空的 int,所以给 sum 一个 int?由于输入只给出相同的错误,可能导致 sum 仅适用于整数.
I assume its because sum returns an int and not a nullable int, giving sum a int? as input only give the same error, probably cause sum only workes on ints.
有什么好的解决方法吗?
Any good workaround for this?
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 ?? 0).Sum()
}
编辑 - 好吧,这个怎么样...(再次拍摄,因为我不知道你的型号...):
EDIT - ok what about this... (Shooting again since I don't know your model...):
from i in Db.Items
select new VotedItem
{
ItemId = i.ItemId,
Points = (from v in Db.Votes
where b.ItemId == v.ItemId)
.Sum(v => v.Points)
}
这篇关于总和可为空的 Linq 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!