Question

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.

Was it helpful?

Solution

In VB.NET, IIf() evaluates every one of its arguments since it's a function, not a language statement. So inv.Record.Pack_Num = PSNum will always be evaluated.

You can use If() instead of IIf() (same syntax) which uses short-circuiting evaluation so everything will work as expected.

On a side node, be careful with And and Or which have the same behavior. Use AndAlso and OrElse instead if you need short-circuiting evaluation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top