本文介绍了的NullReferenceException即使IsDBNull以便在经过检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

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以便首先防止发生此?

When I execute it, it throws an object reference not set to an instance of an object error on getProspect.user_id. Why is it doing this? Shouldn't the fact that I'm verifying it exists using IsDBNull first keep this from happening?

推荐答案

的DBNull 是不一样的没有 没有,和你有什么。 FirstOrDefault ,顾名思义,返回的第一个项目或默认值,即没有引用类型 - 从来没有的DBNull

DBNull is not the same as Nothing, and what you have is Nothing. FirstOrDefault, as the name suggests, returns the first item or the default value, which is Nothing for reference types - never 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

这篇关于的NullReferenceException即使IsDBNull以便在经过检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 10:41