Bill Greer
Bill Greer

Reputation: 3156

How do I make a lambda query nullable?

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);

Upvotes: 5

Views: 6091

Answers (5)

guitarlass
guitarlass

Reputation: 1617

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;

Upvotes: 1

Ravi Patel
Ravi Patel

Reputation: 463

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.

Upvotes: 0

Matt Burland
Matt Burland

Reputation: 45135

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.

Upvotes: 4

evanmcdonnal
evanmcdonnal

Reputation: 48096

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;

Upvotes: 0

Reza
Reza

Reputation: 19863

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;

Upvotes: 2

Related Questions