Mark Fenech Mark Fenech - 1 year ago 106
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 equals od.productId into proDetails
orderby proDetails.Sum(q => q.quantity) descending
select new Common.Views.ProductQuantitySold()
productId =,
productName =,
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 Source

Try replace the following line:

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


qtySold = proDetails.Sum(q => (int?)q.quantity) ?? 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download