即使在使用IsDBNull检查后仍会出现NullReferenceException

时间:2012-05-22 23:11:54

标签: asp.net vb.net

我有以下代码:

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 个答案:

答案 0 :(得分:1)

DBNullNothing不同,您所拥有的是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