2011-04-15 105 views
11

我在尝试获取“预订”的SUM,并收到错误“由于物化值为null,所以转换为值类型'Int32'失败。无论是结果类型的泛型参数还是查询必须使用可空类型。“使用LINQ SUM时出现异常

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

我该如何解决这个问题?如果它没有预订,我需要得到0。

+0

同样的问题在这里:http://stackoverflow.com/questions/2076827/linq-error-generic-pa- ter----query-must-use-a-nullable-type – VikciaR 2011-04-15 10:18:46

回答

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。

+0

在我的情况下,它也返回int,而不是nullable int,这是没有意义的。如何? 0修复它呢? – Zapnologica 2016-11-24 20:12:53

1

添加检查null。

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

选择*从预订WHERE BookingQuantity IS NULL返回0行,所以如果有的话全部有1个或更多。 – 2011-04-15 09:58:03

15

This page建议解决此问题;

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

我的编译器抛出一个错误说'??不能应用于int' – Zapnologica 2016-11-24 20:19:31

+0

您是否将它投射到(in​​t?)? – 2016-11-25 20:43:35

相关问题