When using LINQ SUM, an exception occurs.

entity-framework linq

Question

To determine the SUM of "reservations" and I get the error "The cast to value type 'Int32' failed because the materialized value is null. The query must utilize a nullable type, or the generic parameter of the return type must."

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

How do I make this right? If it ever becomes null, I must get 0; else, bookings will occur.

1
11
11/24/2016 8:22:10 PM

Accepted Answer

A null coalescing operator could be useful:

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 define reservations to be a nullable int.

int? reservations =...

The result of Sum is being recognized by the compiler's type inference as a simple int, which should never be null.

41
4/15/2011 10:02:07 AM

Popular Answer

this website offers a solution to this issue;

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow