2017-04-06 67 views
1

使用依赖于旧版本实体的应用程序,并试图将NULL插入到int字段中。 SQL Server中的字段是(int, null)使用VB.Net和EF5插入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领域,但仍然进行了相当一部分的研究,因此我觉得我的问题具体到足以证明自己的问题。

谢谢。

+0

更改代码,以便您只在记录中添加一个值,如果它是数字,即:'If IsNumeric(txtAppID.Text)Then applications.application_id = CInt(txtAppID.Text)' –

+0

@LaughingVergil我应该提到这也用于更新。使用该方法将意味着使用无法*删除*应用程序ID,因为如果它们消除了字段并更新,'applications.application_id'将不会被设置。 – Santi

回答

1

IIf功能不短路,因此总是评估真假部分,所以它不会在这种情况下工作。关键字If短路,但您可能会遇到返回类型和可为空值类型的问题(例如Dim x As Integer? = If(False, 1, Nothing)结果为x = 0,因为If返回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 

和使用:

applications.application_id = NullableCInt(txtAppID.Text) 
+0

欣赏它,多么糟糕的疏忽!我通过简单地将Dim AppID设置为Integer来修复它? = IIf(IsNumeric(txtAppID.Text),txtAppID.Text,Nothing)'和'applications.application_id = AppID',它似乎工作得很好。 – Santi

+1

您可能希望打开'Option Strict On',它不允许像那样进行隐式转换,但会产生更健壮的代码。 – Mark

+0

正确,我很快地说我的方法在测试所有案例之前就工作了。我其实非常喜欢法比奥的解决方案,但是你的解决方案并不错。感谢您的意见,并在此向我指出正确的方向。 – Santi

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你需要“检查/转换”字符串只有一次整数。

+0

这是干净的,适用于所有情况。谢谢! – Santi