Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception when using LINQ SUM

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.

like image 558
Lasse Edsvik Avatar asked Apr 15 '11 09:04

Lasse Edsvik


2 Answers

Try the null coalescing operator:

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

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.

like image 179
Simon Gill Avatar answered Oct 19 '22 12:10

Simon Gill


This page suggests a fix to this problem;

Sum(x => (int?)x.BookingQuantity) ?? 0;
like image 25
Chris McAtackney Avatar answered Oct 19 '22 14:10

Chris McAtackney