Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a lambda query nullable?

Tags:

c#

lambda

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);
like image 490
Bill Greer Avatar asked Apr 24 '14 17:04

Bill Greer


3 Answers

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.

like image 122
Matt Burland Avatar answered Oct 29 '22 11:10

Matt Burland


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;
like image 36
Reza Avatar answered Oct 29 '22 09:10

Reza


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;
like image 26
guitarlass Avatar answered Oct 29 '22 11:10

guitarlass