from i in Db.Items
select new VotedItem
{
ItemId = i.ItemId,
Points = (from v in Db.Votes
where b.ItemId == v.ItemId
select v.Poi
Just to add another method into the mix :)
Where(q=> q.ItemId == b.ItemId && b.Points.HasValue).Sum(q=>q.Points.Value)
I had a similar scenario but I wasn't comparing an additional field when summing...
Where(q => q.FinalValue.HasValue).Sum(q=>q.FinalValue.Value);
You want to use the nullable form of Sum, so try casting your value to a nullable:
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)
}
Your issue is discussed here in more detail:
http://weblogs.asp.net/zeeshanhirani/archive/2008/07/15/applying-aggregates-to-empty-collections-causes-exception-in-linq-to-sql.aspx
I had a similar issue and came up with the solution of getting whatever I was trying to get out of the database, do a count on those and then only if I had anything returned do a sum. Wasn't able to get the cast working for some reason so posting this if anyone else had similar issues.
e.g.
Votes = (from v in Db.Votes
where b.ItemId = v.ItemId
select v)
And then check to see if you've got any results so that you don't get null returned.
If (Votes.Count > 0) Then
Points = Votes.Sum(Function(v) v.Points)
End If
Thought I would throw another solution out there. I had a similar issue and this is how I ended up solving it:
Where(a => a.ItemId == b.ItemId && !b.IsPointsNull()).Sum(b => b.Points)
Assuming "v.Points" is a decimal just use the following:
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
}
Try to check this out:
var count = db.Cart.Where(c => c.UserName == "Name").Sum(c => (int?)c.Count) ?? 0;
So, the root of the problem is that SQL query like this:
SELECT SUM([Votes].[Value])
FROM [dbo].[Votes] AS [Votes]
WHERE 1 = [Votes].[UserId]
returns NULL