When running the following Linq query
ViewBag.AmountThisYear = db.Bookings
.Where(p => p.Id == id &&
p.StartDate.Year == DateTime.Now.Year)
.Sum(t => t.Price);
I am getting the following error when there are no results returned in the where clause
The cast to value type 'System.Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
How should the Sum be written to cope with this situation
Since no rows are returned you cannot sum. You could use DefaultIfEmpty
:
ViewBag.AmountThisYear = db.Bookings
.Where(p => p.Id == id &&
p.StartDate.Year == DateTime.Now.Year)
.Select(t => t.Price)
.DefaultIfEmpty(0)
.Sum();
If the calculating field is not nullable, then you need to cast nullable first for calculation. So the change will be like this below:
ViewBag.AmountThisYear = db.Bookings
.Where(p => p.Id == id &&
p.StartDate.Year == DateTime.Now.Year)
.Sum(t => (decimal?)t.Price) ?? 0m;
Also, add coalesce operator (??) to translate null to 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With