c# – Linq查询与可空的和

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而不是一个nullable int,给sum一个int?作为输入只给出相同的错误,可能导致总和只工作int。

任何好的解决方法为此?

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

编辑 – 确定这个…(拍摄,因为我不知道你的模型…):

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) 
}
http://stackoverflow.com/questions/696431/linq-query-with-nullable-sum

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – Linq查询与可空的和