使用 LINQ to DataSet 时出现 DBNull 问题
我有以下 LINQ 语句:
Dim PSNum As Integer = 66
Dim InvSeq = (From invRecord In InvSeqDataSet.RptInvSeqDT.AsQueryable() _
Where IIf(invRecord.IsPack_NumNull(), False, invRecord.Pack_Num = PSNum) _
Select New With _
{.Inv = invRecord.Invoice_Num, .Seq = invRecord.Inv_Seq}).FirstOrDefault()
invRecord.Pack_Num 是 Integer 类型的字段。这意味着当我尝试访问它时,如果它是 DBNull,我会收到 StronglyTypedException。上面的代码抛出了这个异常。但是,如果我删除“invRecord.Pack_Num = PSNum”并在其位置放置类似“True”的内容,则代码可以正常工作。
所以我想我的问题是,为什么当值实际上是 DBNull 时 invRecord.IsPack_NumNull() 返回 False ,我可以使用什么作为条件?我已经把头撞在墙上有一段时间了,但找不到解决这个问题的方法。
I've got the following LINQ Statement:
Dim PSNum As Integer = 66
Dim InvSeq = (From invRecord In InvSeqDataSet.RptInvSeqDT.AsQueryable() _
Where IIf(invRecord.IsPack_NumNull(), False, invRecord.Pack_Num = PSNum) _
Select New With _
{.Inv = invRecord.Invoice_Num, .Seq = invRecord.Inv_Seq}).FirstOrDefault()
invRecord.Pack_Num is a field of type Integer. This means that when I try to access it, if it is DBNull I get a StronglyTypedException. The above code throws this exception. If, however, I remove the "invRecord.Pack_Num = PSNum" and in its place put something like "True", the code works fine.
So I guess my question is, why is that that invRecord.IsPack_NumNull() returns False when the value is in fact DBNull and what can I use as a conditional instead? I've been beating my head against the wall for a while now and I can't find a solution to this problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 VB.NET 中,
IIf()
计算其每个参数,因为它是一个函数,而不是一个语言语句。因此inv.Record.Pack_Num = PSNum
将始终被评估。您可以使用
If()
而不是IIf()
(相同语法),它使用短路评估,因此一切都会按预期工作。在侧节点上,请小心具有相同行为的
And
和Or
。如果需要短路评估,请改用AndAlso
和OrElse
。In VB.NET,
IIf()
evaluates every one of its arguments since it's a function, not a language statement. Soinv.Record.Pack_Num = PSNum
will always be evaluated.You can use
If()
instead ofIIf()
(same syntax) which uses short-circuiting evaluation so everything will work as expected.On a side node, be careful with
And
andOr
which have the same behavior. UseAndAlso
andOrElse
instead if you need short-circuiting evaluation.