EF Linq Product Sum when no records returned
Posted
by
user1622713
on Stack Overflow
See other posts from Stack Overflow
or by user1622713
Published on 2012-11-25T10:07:57Z
Indexed on
2012/11/25
11:04 UTC
Read the original article
Hit count: 136
I’ve seen variations of this question all over the place but none of the answers work for me. Most of them are just trying to sum a single column too – nothing more complex such as the sum of a product as below:
public double Total
{
get
{
return _Context.Sales.Where(t => t.Quantity > 0)
.DefaultIfEmpty()
.Sum(t => t.Quantity * t.Price);
}
}
If no rows are returned I want to return zero. However if no rows are returned the .Sum() fails. There are various options of trying to insert Convert.ToDouble and using null coalesce operators, but they all still gave me errors.
I’m sure I am missing a simple way to do this – any help greatly appreciated after too long banging head against google brick wall!
© Stack Overflow or respective owner