使用 LINQ SUM 时出现异常
我试图获取“bookings”的总和,但收到错误“转换为值类型‘Int32’失败,因为物化值为空。结果类型的通用参数或查询必须使用可为空的类型。”
var bookings = entities.Bookings.Where(x => x.ID == id &&
x.StartDate <= bookingEnd &&
x.EndDate >= bookingStart)
.Sum(x => x.BookingQuantity);
我该如何解决这个问题?如果它的预订为空,我需要得到 0。
I'm trying to get the SUM of "bookings" and I get error "The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."
var bookings = entities.Bookings.Where(x => x.ID == id &&
x.StartDate <= bookingEnd &&
x.EndDate >= bookingStart)
.Sum(x => x.BookingQuantity);
How shall I fix this? I need to get 0 if it ever gets to be null else its bookings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用 null 合并运算符:
或者将 bookings 声明为可空 int
int? bookings = ...
编译器类型推断将 Sum 的结果拾取为普通 int,它永远不应该为 null。
Try the null coalescing operator:
or declare bookings as a nullable int
int? bookings = ...
The compilers type inference is picking up the result of Sum as a plain int, which should never be null.
此页面建议解决此问题;
This page suggests a fix to this problem;
添加空值检查。
Add checking for null.