我有以下 LINQ 查询
from p in dc.Purchases
where invoiceNumber == null || p.InvNumber == invoiceNumber.Value
select p;
'invoiceNumber' 是一个可以为 null 的 int - 当它为 null 时,程序会抛出一个 'Nullable object must have a value error'。当它首先明确检查它是否为 null 时,为什么会这样?有解决办法吗?
谢谢,
最佳答案
我认为您的查询有问题。根据您提供的代码,我假设 invoiceNumber
是局部变量或参数。如果是这种情况,那么您为什么还要在查询中检查 invoiceNumber == null
呢?此类检查应与查询分开进行:
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;
}
关于c# - 可为空的对象必须有一个值——为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10207023/