如果我这样做:
int updateGamePlays = db.tblArcadeGames.Where(c => c.ParentGameID == GameID).Sum(c => c.Plays);
如果此查询中没有返回记录,则抛出:
System.InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.
让它返回 0 的唯一方法是执行以下操作:
int updateGamePlays = db.tblArcadeGames.Where(c => c.ParentGameID == GameID).Sum(c => (int?)c.Plays) ?? 0;
在数据库
c.Plays
是一个不可为空的 int。在集合论中,空集的总和应该等于
0
( ref )。他们如何决定在 Linq-to-SQL 中返回 null
?
最佳答案
According to a source at Microsoft , 空集上的 Sum() 是 null
因为它在 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.
关于linq - 为什么空集的总和为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8663580/