您想要使用可以为空的Sum形式,因此请尝试将您的值转换为可为空的:
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
您想要使用可以为空的Sum形式,因此请尝试将您的值转换为可为空的:
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
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) }
假设"v.Points"是小数,只需使用以下代码:
from i in Db.Items select new VotedItem { ItemId = i.ItemId, Points = (from v in Db.Votes where b.ItemId == v.ItemId select (decimal?) v.Points).Sum() ?? 0 }
如果你不喜欢转换为nullabe十进制,你也可以尝试使用Linq To Objects和ToList()方法,
LinqToObjects空集合的总和为0,其中LinqToSql空集合的总和为空.
试着看看这个:
var count = db.Cart.Where(c => c.UserName == "Name").Sum(c => (int?)c.Count) ?? 0;
所以,问题的根源是SQL查询,如下所示:
SELECT SUM([Votes].[Value]) FROM [dbo].[Votes] AS [Votes] WHERE 1 = [Votes].[UserId]
返回NULL
一个简单但有效的解决方法是只对Points.Count> 0的投票求和,所以你永远不会有空值:
from i in Db.Items select new VotedItem { ItemId = i.ItemId, Points = (from v in Db.Votes where b.ItemId == v.ItemId && v.Points.Count > 0 select v.Points).Sum() }