The Linq.Sum () function does not work when there is nothing

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 get the following error when there are no results returned in the where clause

An attribute like "System.Decimal" is invalid because the materialized value is zero. Either the general parameter of the result type or the query should use a type with a null value.

How Sum Should Be Written To Deal With This Situation

+4
source share
3 answers

Since no rows are returned, you cannot sum. You can use DefaultIfEmpty:

ViewBag.AmountThisYear = db.Bookings
            .Where(p => p.Id == id && 
                        p.StartDate.Year == DateTime.Now.Year)
            .Select(t => t.Price)
            .DefaultIfEmpty(0)
            .Sum();
+12
source
decimal sum = 0;
var booking = db.Bookings
        .Where(p => p.Id == id && 
                    p.StartDate.Year == DateTime.Now.Year);


if(bookings.Any())
{
    sum = booking.Sum(t => t.Price);
}

ViewBag.AmountThisYear = sum;

0
source

NULL, NULL. , :

ViewBag.AmountThisYear = db.Bookings
            .Where(p => p.Id == id && 
                        p.StartDate.Year == DateTime.Now.Year)
            .Sum(t => (decimal?)t.Price) ?? 0m;

, (??) 0.

0

Source: https://habr.com/ru/post/1589159/


All Articles