2012-05-22 39 views
0

檢查後我有以下代碼:的NullReferenceException即使IsDBNull以便

Dim getProspect = (From p In dbContext.IRF_Prospects _ 
        Where p.url = prospect_url _ 
        Select p).FirstOrDefault 
' If they have a record... 
If Not IsDBNull(getProspect) Then 
    If IsDBNull(getProspect.user_id) Then 
     ' Prepopulate the form with their information. 
     txtFirst.Text = getProspect.first_name 
Else 
     ' Redirect them to login. 
     Response.Redirect("login.aspx") 
End If 

當我執行它,它拋出一個對象引用不設置爲一個對象錯誤的實例上getProspect.user_id。它爲什麼這樣做?不應該使用IsDBNull首先驗證它是否存在這一事實?

回答

1

DBNull是不一樣的Nothing,你有什麼是Nothing。如名稱所示,FirstOrDefault返回第一項或默認值,即Nothing作爲參考類型 - 從不DBNull

Dim getProspect = (From p In dbContext.IRF_Prospects _ 
        Where p.url = prospect_url _ 
        Select p).FirstOrDefault 
' If they have a record... 
If getProspect IsNot Nothing Then 
    If IsDBNull(getProspect.user_id) Then 
     ' Prepopulate the form with their information. 
     txtFirst.Text = getProspect.first_name 
    Else 
     ' Redirect them to login. 
     Response.Redirect("login.aspx") 
    End If