Sum and Count in EF

It bugs me that I need to play around with casting in linq expressions just to make aggregate functions safe. For example:

decimal? total = storeDb.Carts
                   .Where(cart => cart.CartId == ShoppingCartId)
                   .Select(c => (decimal ?)c.Count * c.Album.Price)
                   .Sum();

See that (decimal ?) cast?

If you haven’t encountered it before, it’s because of what will happen if the result of the query is a null list:

The cast to value type ‘Decimal’ failed because the materialized value is null

It only happens when linq to sql gets involved, a linq object query against objects in an array (say) would be fine…

And no, neither of the fields in the database are nullable

This entry was posted in EF and tagged , , , . Bookmark the permalink.

Leave a Reply