Question

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);
Was it helpful?

Solution

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.

OTHER TIPS

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;

The error indicates that d.QtyOnOrder is not nullable so the solution is to change the class definition so that it is an int? (short hand for Nullable<int>) or to use the null coalescing operator on the left hand side to ensure that null is never returned;

db.DieOrders.Where(c=>c.DrawDie.SizeUS==d.SizeUS).Sum(c => c.QtyOpen) ?? 0;

If the datatype of "QtyOnOrder" is int, You should make it as int?. So now even if sum returns null, code do not generate any error.

int? is a nullable datatype. To know about Nullable types Visit Nullable Types.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top