【问题标题】:Conversion from type 'DBNull' to type 'Integer' is not valid in designer [duplicate]从“DBNull”类型到“Integer”类型的转换在设计器中无效[重复]
【发布时间】:2016-04-04 22:31:40
【问题描述】:

我在下面的实体类中有一个代码。它在 Entity.Designer.vb 中抛出异常,说 Table Patient 中的值 Amount 是 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

它进入如下的“返回”行并抛出异常。

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

异常详情是

Microsoft.VisualBasic.dll 中发生了“System.InvalidCastException”类型的第一次机会异常

附加信息:从“DBNull”类型到“Integer”类型的转换无效。

【问题讨论】:

  • 您的第一个块似乎不完整/搞砸了。
  • @Plutonix:嗨,Plutonix,我只是更改了一些名称,仅此而已。这是 dbnull 到整数转换的错误。他们到处都有这个,但我担心只有在这个地方它会抛出错误,因为我使用了这个专栏。有什么建议可以解决吗?
  • @Plutonix:已更正
  • 没有。 If _patientDetails.Amount 的 If 块格式不正确。行不以Then 开头
  • @Plutonix:这就是我的项目中的内容。正如您所怀疑的那样,它正是它引发异常的位置,但是当控件进入“第一个 If 块”时。显然它正在尝试访问该属性,并且在该属性中,它会引发异常。

标签: .net vb.net exception casting dbnull


【解决方案1】:

最终,确实:您不能将 DBNull 转换为整数。您将需要检查 DBNull,并在这种情况下您希望发生的任何特殊情况。也许将其视为 0 或 -1,也许做一些不同的事情:只有你知道。

如果这是 C#,我会使用:

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
}

(我的VB-foo很弱,所以我把翻译留给读者练习)

【讨论】:

    【解决方案2】:

    试试这个:

        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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-07
      • 2014-06-10
      • 2012-11-19
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多