DataAdapter.AcceptChangesDuringUpdate 属性

定义

获取或设置在 AcceptChanges() 期间是否调用 Update(DataSet)Gets or sets whether AcceptChanges() is called during a Update(DataSet).

public:
 property bool AcceptChangesDuringUpdate { bool get(); void set(bool value); };
public bool AcceptChangesDuringUpdate { get; set; }
member this.AcceptChangesDuringUpdate : bool with get, set
Public Property AcceptChangesDuringUpdate As Boolean

属性值

如果在 true 期间调用 AcceptChanges(),则为 Update(DataSet);否则为 falsetrue if AcceptChanges() is called during an Update(DataSet); otherwise false. 默认为 trueThe default is true.

示例

此示例演示从 DataTable 中提取已更改的行,然后使用 SqlDataAdapter 更新数据源并检索新标识列值。This example demonstrates extracting changed rows from a DataTable and using a SqlDataAdapter to update the data source and retrieve a new identity column value. 通过将 SqlDataAdapterAcceptChangesDuringUpdate 属性设置为 false 保留原始的自动增量值,即使新的标识值与 DataTable中的原始自动增量值不匹配,也可以将新数据合并到原始的 DataTable中。By setting the AcceptChangesDuringUpdate property of the SqlDataAdapter to false to preserve the original auto increment value, the new data can then be merged into the original DataTable, even if the new identity value does not match the original auto increment value in the DataTable.

private static void MergeIdentityColumns(string connectionString)
{
    using (SqlConnection connection =
               new SqlConnection(connectionString))
    {
        // Create the DataAdapter
        SqlDataAdapter adapter =
            new SqlDataAdapter(
            "SELECT ShipperID, CompanyName FROM dbo.Shippers",
            connection);

        //Add the InsertCommand to retrieve new identity value.
        adapter.InsertCommand = new SqlCommand(
            "INSERT INTO dbo.Shippers (CompanyName) " +
            "VALUES (@CompanyName); " +
            "SELECT ShipperID, CompanyName FROM dbo.Shippers " +
            "WHERE ShipperID = SCOPE_IDENTITY();", connection);

        // Set AcceptChangesDuringUpdate to false
        adapter.AcceptChangesDuringUpdate = false;

        // Add the parameter for the inserted value.
        adapter.InsertCommand.Parameters.Add(
           new SqlParameter("@CompanyName", SqlDbType.NVarChar, 40,
           "CompanyName"));
        adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.Both;

        // MissingSchemaAction adds any missing schema to
        // the DataTable, including auto increment columns
        adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

        // Fill a DataTable.
        DataTable shipper = new DataTable();
        adapter.Fill(shipper);

        // Add a new shipper row.
        DataRow newRow = shipper.NewRow();
        newRow["CompanyName"] = "New Shipper";
        shipper.Rows.Add(newRow);

        // Add changed rows to a new DataTable. This
        // DataTable will be used to update the data source.
        DataTable dataChanges = shipper.GetChanges();

        adapter.Update(dataChanges);
        connection.Close();

        Console.WriteLine("Rows after merge.");
        foreach (DataRow rowBefore in shipper.Rows)
        {
            {
                Console.WriteLine("{0}: {1}", rowBefore[0], rowBefore[1]);
            }
        }

        // Merge the two DataTables to get new values.
        shipper.Merge(dataChanges);

        // Commit the changes.
        shipper.AcceptChanges();

        Console.WriteLine("Rows after merge.");
        foreach (DataRow rowAfter in shipper.Rows)
        {
            {
                Console.WriteLine("{0}: {1}", rowAfter[0], rowAfter[1]);
            }
        }
    }
}
Private Sub MergeIdentityColumns(ByVal connectionString As String)

    Using connection As SqlConnection = New SqlConnection( _
       connectionString)

        ' Create the DataAdapter
        Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
          "SELECT ShipperID, CompanyName FROM dbo.Shippers", connection)

        ' Add the InsertCommand to retrieve new identity value.
        adapter.InsertCommand = New SqlCommand( _
            "INSERT INTO dbo.Shippers (CompanyName) " & _
            "VALUES (@CompanyName); " & _
            "SELECT ShipperID, CompanyName FROM dbo.Shippers " & _
            "WHERE ShipperID = SCOPE_IDENTITY();", _
            connection)

        ' Set AcceptChangesDuringUpdate to false.
        adapter.AcceptChangesDuringUpdate = False

        ' Add the parameter for the inserted value.
        adapter.InsertCommand.Parameters.Add( _
           New SqlParameter("@CompanyName", SqlDbType.NVarChar, 40, _
           "CompanyName"))
        adapter.InsertCommand.UpdatedRowSource = _
           UpdateRowSource.FirstReturnedRecord

        ' MissingSchemaAction adds any missing schema to 
        ' the DataTable, including auto increment columns
        adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey

        ' Fill a DataTable.
        Dim shipper As New DataTable
        adapter.Fill(shipper)

        ' Add a new shipper row. 
        Dim newRow As DataRow = shipper.NewRow()
        newRow("CompanyName") = "New Shipper"
        shipper.Rows.Add(newRow)

        ' Add changed rows to a new DataTable. This
        ' DataTable will be used to update the data source.
        Dim dataChanges As DataTable = shipper.GetChanges()

        ' Update the data source with the modified records.
        adapter.Update(dataChanges)

        Console.WriteLine("Rows before merge.")
        Dim rowBefore As DataRow
        For Each rowBefore In shipper.Rows
            Console.WriteLine("{0}: {1}", rowBefore(0), rowBefore(1))
        Next

        ' Merge the two DataTables to get new values.
        shipper.Merge(dataChanges)

        ' Commit the changes.
        shipper.AcceptChanges()

        Console.WriteLine("Rows after merge.")
        Dim rowAfter As DataRow
        For Each rowAfter In shipper.Rows
            Console.WriteLine("{0}: {1}", rowAfter(0), rowAfter(1))
        Next
    End Using
End Sub

注解

在对 DataAdapterUpdate 方法的调用过程中,数据库可以将数据作为输出参数发送回 ADO.NET 应用程序,或将其作为结果集的第一个返回记录返回。During a call to the Update method of a DataAdapter, the database can send data back to your ADO.NET application as output parameters or as the first returned record of a result set. ADO.NET 可以检索这些值并在要更新的 DataRow 中更新相应的列。ADO.NET can retrieve these values and update the corresponding columns in the DataRow being updated. 默认情况下,ADO.NET 将在更新后调用 DataRowAcceptChanges 方法。By default, ADO.NET calls the AcceptChanges method of the DataRow after the update. 但是,如果想要将更新的行合并回另一个 DataTable,则可能需要保留主键列的原始值。However, if you want to merge the updated row back into another DataTable, you may want to preserver the original value of a primary key column. 例如,与数据库中自动递增的列(例如,标识列)相对应的主键列可以包含与 DataRow中分配的原始值不匹配的新值。For example, a primary key column corresponding to an automatically incrementing column in the database, such as an identity column, can contain new values that are assigned by the database that do not match the original values assigned in the DataRow. 默认情况下,AcceptChanges 是在更新后隐式调用的,并且行中的原始值(可能已 AutoIncrement ADO.NET 分配的值)将丢失。By default, AcceptChanges is called implicitly after an update, and the original values in the row, which may have been AutoIncrement values assigned by ADO.NET, are lost. 您可以通过将 AcceptChangesDuringUpdate 属性设置为 false来保留原始值,从而在 DataRow 中保留原始值,方法是防止 ADO.NET 在对行执行更新后调用 AcceptChangesYou can preserve the original values in the DataRow by preventing ADO.NET from calling AcceptChanges after it performs an update on a row, by setting the AcceptChangesDuringUpdate property to false, which preserves the original values.

备注

AcceptChangesDuringUpdate 属性设置为 false 适用于所有数据修改,而不只是 insert。Setting the AcceptChangesDuringUpdate property to false applies to all data modifications, not only inserts. 如果要在同一更新中编辑或删除行,并且想要取消对 AcceptChanges 的调用,而不是将 AcceptChangesDuringUpdate 设置为 false,请使用事件处理程序来处理 DataAdapterRowUpdated 事件。If you want to edit or delete rows in the same update, and if you want to suppress the call to AcceptChanges only for inserts, then instead of setting AcceptChangesDuringUpdate to false, use an event handler for the RowUpdated event of the DataAdapter. 在事件处理程序中,您可以检查 StatementType 来确定数据修改是否为插入,如果 true,则将 RowUpdatedEventArgsStatus 属性设置为 SkipCurrentRowIn the event handler, you can check the StatementType to determine if the data modification is an insert, and if true, set the Status property of the RowUpdatedEventArgs to SkipCurrentRow. 有关详细信息和示例,请参阅检索标识或自动编号值For more information and an example, see Retrieving Identity or Autonumber Values.

适用于

另请参阅