The confusion is due to the fact that Sum in LINQ To Entities is handled a little differently than in LINQ To Objects. Although from the declaration it looks like it is calling it, let it be said that decimal will return 0 when the target set is empty, the SQL Sum function returns NULL , even if the target column is not NULL.
Once you know this, there are two ways to solve it.
Say we have a table with a decimal column, and the original expression
table.Sum(item => item.Column)
The first way is to convert it using the template contained in Maarten's answer:
table.Select(item => item.Column).DefaultIfEmpty().Sum()
The second way is to explicitly convert the type with a null value to a NULL value inside the function, and then apply the null coalescing operator to the result :
table.Sum(item => (decimal?)item.Column) ?? 0
Both methods work and produce the same result, so use the one that best suits your personal preferences.
For completeness of application of the second approach in your case will basically move ?? 0 ?? 0 outside Sum call:
decimal foodCount = dbContext.fad_userFoods .Where(uf => uf.dateAdded == thisDate && uf.userID == thisGuid) .Sum(uf => (decimal?)uf.quantityAmount) ?? 0;
source share