11

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.

1

3 Answers 3

41

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In my case it also returns int, not nullable int which doesn't make sense. How does the ?? 0 fix it then?
15

This page suggests a fix to this problem;

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

2 Comments

my compiler throws an error saying '?? cannot be applied to type int'
Did you cast it to (int?) ?
1

Add checking for null.

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

1 Comment

SELECT * FROM Bookings WHERE BookingQuantity IS NULL returns 0 rows, so all have 1 or more if there are any.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.