我试图获得"预订"的总和,我得到错误"转换到值类型'Int32'失败,因为物化值为空。结果类型的泛型参数或查询必须使用可空类型。"
var bookings = entities.Bookings.Where(x => x.ID == id &&
x.StartDate <= bookingEnd &&
x.EndDate >= bookingStart)
.Sum(x => x.BookingQuantity);
我该如何解决这个问题?如果它为空,我需要得到0否则它的预订
尝试null合并运算符:
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
int ?
编译器的类型推断将Sum的结果提取为普通int,该int不应该为null。
此页面建议修复此问题;
Sum(x => (int?)x.BookingQuantity) ?? 0;
添加null检查。
var bookings = entities.Bookings.Where(x => x.ID == id &&
x.StartDate <= bookingEnd &&
x.EndDate >= bookingStart &&
x.BookingQuantity != null)
.Sum(x => x.BookingQuantity);