If I do:
int updateGamePlays = db.tblArcadeGames.Where(c => c.ParentGameID == GameID).Sum(c => c.Plays);
If no records are returned in this query it throws:
System.InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.
The only way to get it to return 0 is by doing:
int updateGamePlays = db.tblArcadeGames.Where(c => c.ParentGameID == GameID).Sum(c => (int?)c.Plays) ?? 0;
In the database c.Plays
is a non-nullable int.
In set theory the sum of an empty set should equal 0
(ref). How comes in Linq-to-SQL did they decide to make it return null
?
In mathematical sets, the null set, also called the empty set, is the set that does not contain anything. It is symbolized or { }. There is only one null set. This is because there is logically only one way that a set can contain nothing.
You could say that an empty sum is 0 because 0 is the additive identity and an empty product is 1 because 1 is the multiplicative identity.
The null sign (∅) is often used in mathematics for denoting the empty set (however, the variant. seems more commonly used). The same letter in linguistics represents zero, the lack of an element. It is commonly used in phonology, morphology, and syntax.
Every nonempty set has at least two subsets, 0 and itself. The empty set has only one, itself. The empty set is a subset of any other set, but not necessarily an element of it.
According to a source at Microsoft, Sum() on an empty set is null
because of the way it works in SQL:
when the table is empty i´m getting this exception: InvalidOperationException
In SQL, Sum() aggregate operator returns null for an empty set. So this is as designed.
Another alternative is to add a 0 to the set to make sure there's always at least one value.
int updateGamePlays = db.tblArcadeGames.Where(c => c.ParentGameID == GameID)
.Select(c => c.Plays)
.Concat(new [] { 0 })
.Sum();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With