linq - 为什么空集的总和为空?

标签 linq math linq-to-sql sum set

如果我这样做:

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/

相关文章:

linq - 有没有理由在 Linq 上使用实体 SQL?

c# - 将 IEnumerable 转换/转换为 IEnumerable<T>

c# - 无法从 Expression< Func < Entity, bool>> 转换为 Func < Entity, bool>

c# - 如何在不先将整个列表加载到内存的情况下使用 Linq to Sql 实现 SkipWhile?

c# - 您能否使用 Linq-to-SQL 获得类似 DataReader 的流?

linq - 简单(哑)LINQ 提供程序

c++ - 如何确定 Mandelbrot 集缩放的良好中心

java - 有没有一种简单的方法来反转发生溢出的整数函数?

math - 从月份编号获取会计季度

sql - nvarchar 类型的唯一列