Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable object must have a value - why?

I have the following LINQ query

from p in dc.Purchases
where invoiceNumber == null || p.InvNumber == invoiceNumber.Value
select p;

The 'invoiceNumber' is a nullable int - when it's null, the program throws a 'Nullable object must have a value error'. Why is this when it's explicitly checking if it's null first? Is there a way around this?

Thanks,

like image 904
Chris Avatar asked Nov 05 '22 01:11

Chris


1 Answers

I think there is something wrong with your query. From the code you've supplied I assume that invoiceNumber is a local variable or a parameter. If this is the case, then why are you even checking if invoiceNumber == null in your query? Such check should be done separately from the query:

if(invoiceNumber == null)
{
    return dc.Purchases; 
    // the query would evaluate to this because invoiceNumber == null will allways return true.
}
else
{
    return 
        from p in dc.Purchases 
        where p.InvNumber == invoiceNumber.Value
        select p;
}
like image 76
RePierre Avatar answered Nov 09 '22 14:11

RePierre