Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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?

like image 208
Mark Fenech Avatar asked Dec 16 '22 15:12

Mark Fenech


2 Answers

Try replace the following line:

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

to

qtySold = proDetails.Sum(q => (int?)q.quantity) ?? 0
like image 161
Sławomir Rosiek Avatar answered Dec 18 '22 03:12

Sławomir Rosiek


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.

like image 25
Mir Avatar answered Dec 18 '22 04:12

Mir