通过


使用 CommandBuilder 对象时发生 System.NullReferenceException

本文可帮助你解决 System.NullReferenceException 使用 CommandBuilder 对象时发生的异常。

原始产品版本: Visual Basic .NET
原始 KB 数: 310367

症状

如果使用 CommandBuilder 对象来显式获取针对 DataAdapter 对象的命令,如下所示:

da.InsertCommand = cb.GetInsertCommand

然后,运行以下 Visual Basic .NET 代码:

cb.DataAdapter = Nothing

你添加到 DataAdapter 的命令将被删除,并会收到以下错误消息:

app_name.exe 中发生了“System.NullReferenceException”类型的未经处理的异常
其他信息:对象引用未设置为对象的实例。

原因

CommandBuilder 会在从 DataAdapter.CommandBuilderDataAdapter 取消关联或解绑时删除其生成的命令;当它们取消关联或解绑时,命令将被置为 null。 此问题不会影响从头开始生成的命令。

决议

使用以下方法之一来解决此问题:

  • 请勿将CommandBuilderDataSet分离。
  • 在代码中或通过 Visual Data Tools 自行生成命令。

状态

此行为是设计造成的。

重现行为的步骤

  1. 创建新的 Visual Basic .NET Windows 应用程序项目。 Form1 默认添加到项目中。

  2. 向 Form1 添加按钮控件。

  3. 切换到“代码”视图,并将以下代码添加到“代码”窗口顶部:

    Imports System.Data.OleDb
    Imports System.Data.SqlClient
    
  4. 将以下代码添加到 Button 的Click事件:

    Dim con As New SqlConnection("server=myserver;uid=sa;pwd=mypassword;" & _
                                "database=northwind")
    Dim da As New SqlDataAdapter("Select * From Customers", con)
    Dim cb As New SqlCommandBuilder(da)
    Dim cmdInsert As New SqlCommand( _
            "Insert Into Customer (CustomerID) Value ('AAAAA')", con)
    da.InsertCommand = cmdInsert
    da.UpdateCommand = cb.GetUpdateCommand
    da.DeleteCommand = cb.GetDeleteCommand
    Debug.WriteLine(da.InsertCommand.CommandText)
    Debug.WriteLine(da.DeleteCommand.CommandText)
    cb.DataAdapter = Nothing ' Comment out this line to avoid the error.
    cb = Nothing
    Debug.WriteLine(da.InsertCommand.CommandText)
    Debug.WriteLine(da.DeleteCommand.CommandText)'Error occurs here.
    
  5. 根据环境修改连接字符串。

  6. 按 F5 编译并运行应用程序。