Mark Fenech Mark Fenech - 1 month ago 7
ASP.NET (C#) Question

The cast to value type 'Int32' failed null value LINQ

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?

Answer

Try replace the following line:

qtySold = proDetails.Sum(q => q.quantity)

to

qtySold = proDetails.Sum(q => (int?)q.quantity) ?? 0