使用VB.Net和EF5插入NULL整数

时间:2017-04-06 14:41:11

标签: sql-server vb.net entity-framework

处理依赖于旧版本实体的应用程序,我正在尝试将NULL插入int字段。 SQL Server中的字段为(int, null)

这是EF中对象的定义:

<EdmScalarPropertyAttribute(EntityKeyProperty:=false, IsNullable:=true)>
<DataMemberAttribute()>
Public Property application_id() As Nullable(Of Global.System.Int32)

......这就是我要设置它的地方:

applications.application_id = IIf(IsNumeric(txtAppID.Text), CInt(txtAppID.Text), Nothing)

响应中抛出的错误是:

  

在......中发生了'System.InvalidCastException'类型的异常,但未在用户代码中处理

     

其他信息:指定的演员表无效。

我可以确认由于Nothing部分导致此问题被抛出,因为之前它是applications.application_id = CInt(txtAppID.Text)并且一切正常。

我已尝试DBNull.Value而非Nothing,但错误内容相同。虽然大多数问题与ES6或datetime字段有关,但我认为我的问题具体到足以保证自己的问题。

感谢。

2 个答案:

答案 0 :(得分:1)

IIf函数不会短路,因此总是会评估真假部分,因此它不能在那种情况下起作用。 If关键字会短路,但您可能会遇到返回类型和可空值类型的问题(例如Dim x As Integer? = If(False, 1, Nothing)会导致x = 0,因为If正在返回{ {1}}而非Integer)。

所以,我建议使用常规Integer?语句:

If

或者你可以创建一个辅助函数:

If IsNumeric(txtAppID.Text) Then
    applications.application_id = CInt(txtAppID.Text)
Else
    applications.application_id = Nothing
End If

并使用:

Function NullableCInt(value As String) As Integer?
    If IsNumeric(value) Then Return CInt(value)
    Return Nothing
End Function

答案 1 :(得分:1)

您可以使用强制转换

来使用If方法
Dim temp As Integer
applications.application_id = If(Integer.TryParse(value, temp), temp, DirectCast(Nothing, Integer?))

为了更好的可读性,您可以引入“默认”值

Static DEFAULT_VALUE As Integer? = Nothing    
Dim temp As Integer
applications.application_id = If(Integer.TryParse(value, temp), temp, DEFAULT_VALUE)

使用Integer.TryParse,您只需要将字符串“检查/转换”为整数一次。

相关问题