2017-04-06 71 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