使用LINQ SUM时出现异常

时间:2011-04-15 09:53:56

标签: linq entity-framework

我正在尝试获取“预订”的SUM并且我收到错误“强制类型'Int32'的转换失败,因为具体化值为null。结果类型的泛型参数或查询必须使用可空类型。“

var bookings = entities.Bookings.Where(x => x.ID == id &&
                                     x.StartDate <= bookingEnd &&
                                     x.EndDate >= bookingStart)
                                    .Sum(x => x.BookingQuantity);

我该如何解决这个问题?我需要得到0如果它的预订是否为空。

3 个答案:

答案 0 :(得分:41)

尝试使用空合并运算符:

var bookings = entities.Bookings.Where(x => x.ID == id &&
                                 x.StartDate <= bookingEnd &&
                                 x.EndDate >= bookingStart && 
                                 x.BookingQuantity != null)
                                .Sum(x => (int?)x.BookingQuantity) ?? 0;

或将预订声明为可以为空的

INT?预订= ...

编译器类型推断将Sum的结果作为普通的int,它永远不应为null。

答案 1 :(得分:15)

This page建议解决此问题;

Sum(x => (int?)x.BookingQuantity) ?? 0;

答案 2 :(得分:1)

添加检查null。

var bookings = entities.Bookings.Where(x => x.ID == id &&
                                     x.StartDate <= bookingEnd &&
                                     x.EndDate >= bookingStart && 
                                     x.BookingQuantity != null)
                                    .Sum(x => x.BookingQuantity);