Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq .Sum() function fails when there is nothing to Sum

Tags:

c#

linq

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

like image 610
Nick Le Page Avatar asked Dec 03 '22 17:12

Nick Le Page


2 Answers

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();
like image 59
Tim Schmelter Avatar answered Jan 21 '23 02:01

Tim Schmelter


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.

like image 39
Rousonur Jaman Avatar answered Jan 21 '23 04:01

Rousonur Jaman