Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query with nullable 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() } 

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. 

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?

like image 518
AndreasN Avatar asked Mar 30 '09 08:03

AndreasN


2 Answers

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

like image 189
Scott Stafford Avatar answered Oct 16 '22 22:10

Scott Stafford


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)  } 
like image 39
Rashack Avatar answered Oct 16 '22 22:10

Rashack