I am getting the following error:
The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
How do I make my lambda expression nullable ?
d.QtyOnOrder = db.DieOrders.Where(c=>c.DrawDie.SizeUS==d.SizeUS).Sum(c => c.QtyOpen);
Update: The code below works. Can someone tell me why the Linq expression works and the Lambda does not ?
var dies = from e in db.DieOrders
where e.DrawDieID == d.ID && e.QtyOpen !=null
select e;
var _qtyOpen = dies.Sum(x => x.QtyOpen);
I like @RezaRahmati's suggestion, but an alternative is:
d.QtyOnOrder = db.DieOrders.Where(c=>c.DrawDie.SizeUS==d.SizeUS && d.QtyOpen.HasValue)
.Sum(c => c.QtyOpen);
If all of the QtyOpen
are null, then you are summing an empty list which will give you zero.
What I like about Reza's answer however, is that it makes it more explicit that you will set the result to zero if the sum is null.
I think the problem is QtyOnOrder
, since Sum
can returns null QtyOnOrder
should be nullable or use this syntax:
d.QtyOnOrder = db.DieOrders.Where(c=>c.DrawDie.SizeUS==d.SizeUS).Sum(c => c.QtyOpen) ?? 0;
I needed to cast as well, for example the following;
d.QtyOnOrder = db.DieOrders.Where(c=>c.DrawDie.SizeUS==d.SizeUS)
.Sum(c => (int?)c.QtyOpen) ?? 0;
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