使用 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.CommandBuilder 关联和 DataAdapter 链接时生成的命令;取消链接或取消关联时,命令将为 null。 此问题不会影响从头开始生成的命令。

解决方法

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

  • 不要取消DataSet关联 CommandBuilder
  • 在代码中或通过 Visual Data Tools 自行生成命令。

Status

此行为是特意这样设计的。

重现行为的步骤

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

  2. 向 Form1 添加按钮控件。

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

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

    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 编译并运行应用程序。