I’m trying to use LINQ to SQL to sum a row in a a resultset returned from a WCF service. I’m able to use LINQ for basic selects, for order by, for filtering, etc. So far so good.
But when I try to Group By / Sum, I get an error message “Value Cannot Be Null” when trying to Take(5) from the query below. (results is non-null and has 1000+s of items, but the query is null when we try to return it:)
EDIT: I’ve removed the invalid cast as mentioned in the answer below, instead selecting the aggregate results into a custom class written to order. Now the page runs without error — but the group by / sum doesn’t work…. I just get the top five highest values in the results, not summed by group. Why?
var query = (from h in results
group h by h.Order into hh
select new TopOrders()
{
Order = hh.Key,
Total= hh.Sum(r => r.Price)
}).OrderByDescending(i => i.Total);
return query.Take(5).ToList();
Only possible wrinkle I can point to is that Order is itself a collection (OrderID, OrderName, etc.) and so I’ve tried grouping explicitly on hh.Key.Order.OrderID and so forth, to no effect.
Anything I’m missing from what you can see? Thanks.
It’s probably that
r.Priceof a few orders is null, so useSum(r => r.Price ?? 0). But it’s a bit of a guess without knowing your data.Edit
It’s so obvious that I overlooked it: you try to cast an IEnumerable of an anonymous type to
List<TopOrders>, which is not possible. But theasoperator producesnullif the cast is not valid. Soqueryitself isnull! Either remove the cast, or createTopOrders in stead of anonymous types.