I am trying to add some values together using a view and LINQ this is my code below
var getProducts = from p in Entity.Products
join od in getOrderDetails on p.id equals od.productId into proDetails
orderby proDetails.Sum(q => q.quantity) descending
select new Common.Views.ProductQuantitySold()
{
productId = p.id,
productName = p.name,
productDesc = p.description,
qtySold = proDetails.Sum(q => q.quantity)
};
return getProducts.Take(10).AsQueryable();
In the line qtySold = proDetails.Sum(q => q.quantity)
I am getting the cast value error. I know it is something about the null or zero but how should I implement it?
Try replace the following line:
qtySold = proDetails.Sum(q => q.quantity)
to
qtySold = proDetails.Sum(q => (int?)q.quantity) ?? 0
I assume it's a compilation error. If it's not, please leave a comment. Try to cast the result of your sum to an int
or to cast every element of proDetails
to an int
.
Examples:
qtySold = (int) proDetails.Sum(q => q.quantity)
Alternatively:
qtySold = proDetails.Cast<int>().Sum(q => q.quantity)
Please let me know if it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With