0

I have a code below in an Entity Class. It throws exception in the Entity.Designer.vb saying the value Amount in Table Patient is DbNull.

    If _patientDetails.ID > 0 Then
        If _patientDetails.Amount = EntityEnums.Patient.Existing
            Then                          
               _patientDetails.SetAmountNull()
        End If
    Catch ex As Exception
        _patientDetails.SetAmountNull()
    End Try

End If

It goes to the "Return" line as below and throws exception.

Public Property Amount() As Integer
    Get
        Try 
            Return CType(Me(Me.tablePatient.AmountIDColumn),Integer)
        Catch e As Global.System.InvalidCastException
            Throw New Global.System.Data.StrongTypingException("The value for column 'AmountIDColumn' in table 'Patient' is D"& _ 
                    "BNull.", e)
        End Try
    End Get
    Set
        Me(Me.tablePatient.AmountIDColumn) = value
    End Set
End Property

Exception Details are

A first chance exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll

Additional information: Conversion from type 'DBNull' to type 'Integer' is not valid.

Jasmine
  • 5,186
  • 16
  • 62
  • 114

2 Answers2

1

Ultimately, indeed: you can't cast from DBNull to integer. You will need to check for DBNull, and special-case whatever you want to happen in that scenario. Perhaps treat it as 0 or -1, perhaps do something different: only you know.

If this was C#, I would use:

var val = tablePatient.AmountIDColumn;
if(val is DBNull) {
    // special-case; return 0, perhaps
} else {
    // cast, etc
    return (int)val; // or Convert.ChangeType, if it is something exotic
}

(my VB-foo is weak, so I'll leave the translation as an exercise for the reader)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

Try this:

    If _patientDetails.ID > 0 Then
        If (Not _patientDetails.IsAmountNull) AndAlso (_patientDetails.Amount = EntityEnums.Patient.Existing) Then
            _patientDetails.SetAmountNull()
        End If
    End If          

    Catch ex As Exception
        _patientDetails.SetAmountNull()
    End Try
shadow
  • 1,883
  • 1
  • 16
  • 24