DataSet.Merge 方法

定义

将指定的 DataSetDataTableDataRow 对象的数组合并到当前的 DataSetDataTable 中。Merges a specified DataSet, DataTable, or array of DataRow objects into the current DataSet or DataTable.

重载

Merge(DataRow[])

DataRow 对象数组合并到当前的 DataSet 中。Merges an array of DataRow objects into the current DataSet.

Merge(DataSet)

将指定的 DataSet 及其架构合并到当前 DataSet 中。Merges a specified DataSet and its schema into the current DataSet.

Merge(DataTable)

将指定的 DataTable 及其架构合并到当前 DataSet 中。Merges a specified DataTable and its schema into the current DataSet.

Merge(DataSet, Boolean)

将指定的 DataSet 及其架构合并到当前 DataSet 中,在此过程中,将根据给定的参数保留或放弃在此 DataSet 中进行的任何更改。Merges a specified DataSet and its schema into the current DataSet, preserving or discarding any changes in this DataSet according to the given argument.

Merge(DataRow[], Boolean, MissingSchemaAction)

DataRow 对象数组合并到当前的 DataSet 中,在此过程中,将根据给定的参数保留或放弃在 DataSet 中进行的更改并处理不兼容的架构。Merges an array of DataRow objects into the current DataSet, preserving or discarding changes in the DataSet and handling an incompatible schema according to the given arguments.

Merge(DataSet, Boolean, MissingSchemaAction)

将指定的 DataSet 及其架构与当前的 DataSet 合并,在此过程中,将根据给定的参数保留或放弃在当前 DataSet 中的更改并处理不兼容的架构。Merges a specified DataSet and its schema with the current DataSet, preserving or discarding changes in the current DataSet and handling an incompatible schema according to the given arguments.

Merge(DataTable, Boolean, MissingSchemaAction)

将指定的 DataTable 及其架构合并到当前的 DataSet 中,在此过程中,将根据给定的参数保留或放弃在 DataSet 中进行的更改并处理不兼容的架构。Merges a specified DataTable and its schema into the current DataSet, preserving or discarding changes in the DataSet and handling an incompatible schema according to the given arguments.

Merge(DataRow[])

DataRow 对象数组合并到当前的 DataSet 中。Merges an array of DataRow objects into the current DataSet.

public:
 void Merge(cli::array <System::Data::DataRow ^> ^ rows);
public void Merge (System.Data.DataRow[] rows);
member this.Merge : System.Data.DataRow[] -> unit
Public Sub Merge (rows As DataRow())

参数

rows
DataRow[]

要合并到 DataRow 中的 DataSet 对象数组。The array of DataRow objects to be merged into the DataSet.

注解

Merge 方法用于合并两个大体类似架构的 DataSet 对象。The Merge method is used to merge two DataSet objects that have largely similar schemas. 通常在客户端应用程序上使用合并,以将数据源中的最新更改合并到现有 DataSet中。A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. 这允许客户端应用程序使用数据源中的最新数据进行刷新 DataSetThis allows the client application to have a refreshed DataSet with the latest data from the data source.

通常在一系列过程的末尾调用 Merge 方法,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataSetThe Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

在客户端应用程序中,通常有一个按钮,用户可以单击该按钮来收集更改的数据并对其进行验证,然后再将其发送回中间层组件。In a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. 在此方案中,首先调用 GetChanges 方法。In this scenario, the GetChanges method is first invoked. 该方法将返回第二个针对验证和合并进行优化 DataSetThat method returns a second DataSet optimized for validating and merging. 此第二个 DataSet 对象只包含已更改的 DataTableDataRow 对象,导致原始 DataSet的子集。This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. 此子集通常较小,因此更有效地传递回中间层组件。This subset is generally smaller and thus more efficiently passed back to a middle-tier component. 然后,中间层组件使用存储过程中的更改来更新原始数据源。The middle-tier component then updates the original data source with the changes through stored procedures. 然后,中间层可以发回包含原始数据的新 DataSet 和数据源中的最新数据(再次运行原始查询),也可以将其从数据源中所做的任何更改发送回。The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (例如,如果数据源自动创建唯一的主键值,则这些值可以传播回客户端应用程序。)在任一情况下,返回的 DataSet 都可以与 Merge 方法一起合并回客户端应用程序的原始 DataSet(For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

调用 Merge 方法时,将比较两个 DataSet 对象的架构,因为架构可能已更改。When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. 例如,在企业对企业方案中,可能已通过自动化过程将新列添加到了 XML 架构。For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. 如果源 DataSet 包含目标中缺少的架构元素(添加 DataColumn 对象),则可以通过将 missingSchemaAction 参数设置为 MissingSchemaAction.Add来将架构元素添加到目标。If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. 在这种情况下,合并的 DataSet 包含添加的架构和数据。In that case, the merged DataSet contains the added schema and data.

合并架构后,数据将合并。After merging schemas, the data is merged.

在将新的源 DataSet 合并到目标时,DataRowState 值为 UnchangedModifiedDeleted 的任何源行都将与具有相同的主键值的目标行匹配。When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. DataRowState 值为 Added 的源行与新源行的主键值相同的新目标行匹配。Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

在合并过程中,将禁用约束。During a merge, constraints are disabled. 如果在合并结束时无法启用任何约束,则会生成 ConstraintException,并在禁用约束时保留合并的数据。If any constraints cannot be enabled at the end of a merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. 在这种情况下,EnforceConstraints 属性设置为 false,所有无效行都标记为 "错误"。In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. 在尝试将 EnforceConstraints 属性重置为 true之前,必须解决这些错误。The errors must be resolved before attempting to reset the EnforceConstraints property to true.

另请参阅

Merge(DataSet)

将指定的 DataSet 及其架构合并到当前 DataSet 中。Merges a specified DataSet and its schema into the current DataSet.

public:
 void Merge(System::Data::DataSet ^ dataSet);
public void Merge (System.Data.DataSet dataSet);
member this.Merge : System.Data.DataSet -> unit

参数

dataSet
DataSet

其数据和架构将被合并的 DataSetThe DataSet whose data and schema will be merged.

异常

无法启用一个或多个约束。One or more constraints cannot be enabled.

dataSetnullThe dataSet is null.

示例

下面的示例使用了 DataSet上的 GetChanges、Update 和 Merge 方法。The following example uses the GetChanges, Update, and Merge methods on a DataSet.

private void DemonstrateMerge() 
{
    // Create a DataSet with one table, two columns, and three rows.
    DataSet dataSet = new DataSet("dataSet");
    DataTable table = new DataTable("Items");
    DataColumn idColumn = new DataColumn("id", 
        Type.GetType("System.Int32"));
    idColumn.AutoIncrement=true;
    DataColumn itemColumn = new DataColumn("Item", 
        Type.GetType("System.Int32"));

    // DataColumn array to set primary key.
    DataColumn[] keyColumn= new DataColumn[1];
    DataRow row;

    // Create variable for temporary DataSet. 
    DataSet changeDataSet;

    // Add columns to table, and table to DataSet.   
    table.Columns.Add(idColumn);
    table.Columns.Add(itemColumn);
    dataSet.Tables.Add(table);

    // Set primary key column.
    keyColumn[0]= idColumn;
    table.PrimaryKey=keyColumn;

    // Add ten rows.
    for(int i = 0; i <10;i++)
    {
        row=table.NewRow();
        row["Item"]= i;
        table.Rows.Add(row);
    }

    // Accept changes.
    dataSet.AcceptChanges();
    PrintValues(dataSet, "Original values");

    // Change two row values.
    table.Rows[0]["Item"]= 50;
    table.Rows[1]["Item"]= 111;

    // Add one row.
    row=table.NewRow();
    row["Item"]=74;
    table.Rows.Add(row);

    // Insert code for error checking. Set one row in error.
    table.Rows[1].RowError= "over 100";
    PrintValues(dataSet, "Modified and New Values");
    // If the table has changes or errors, create a subset DataSet.
    if(dataSet.HasChanges(DataRowState.Modified | 
        DataRowState.Added)& dataSet.HasErrors)
    {
        // Use GetChanges to extract subset.
        changeDataSet = dataSet.GetChanges(
            DataRowState.Modified|DataRowState.Added);
        PrintValues(changeDataSet, "Subset values");
        // Insert code to reconcile errors. In this case reject changes.
        foreach(DataTable changeTable in changeDataSet.Tables)
        {
            if (changeTable.HasErrors)
            {
                foreach(DataRow changeRow in changeTable.Rows)
                {
                    //Console.WriteLine(changeRow["Item"]);
                    if((int)changeRow["Item",
                        DataRowVersion.Current ]> 100)
                    {
                        changeRow.RejectChanges();
                        changeRow.ClearErrors();
                    }
                }
            }
        }
        PrintValues(changeDataSet, "Reconciled subset values");
        // Merge changes back to first DataSet.
        dataSet.Merge(changeDataSet);
        PrintValues(dataSet, "Merged Values");
    }
}

private void PrintValues(DataSet dataSet, string label)
{
    Console.WriteLine("\n" + label);
    foreach(DataTable table in dataSet.Tables)
    {
        Console.WriteLine("TableName: " + table.TableName);
        foreach(DataRow row in table.Rows)
        {
            foreach(DataColumn column in table.Columns)
            {
                Console.Write("\table " + row[column] );
            }
            Console.WriteLine();
        }
    }
}
 Private Sub DemonstrateMerge()
     ' Create a DataSet with one table, two columns, and three rows.
     Dim dataSet As New DataSet("dataSet")
     Dim table As New DataTable("Items")
     Dim idColumn As New DataColumn("id", Type.GetType("System.Int32"))
     idColumn.AutoIncrement = True
     Dim itemColumn As New DataColumn("Item", Type.GetType("System.Int32"))

     ' DataColumn array to set primary key.
     Dim keyColumn(0) As DataColumn
     Dim row As DataRow

     ' Create variable for temporary DataSet. 
     Dim changeDataSet As DataSet

     ' Add columns to table, and table to DataSet.   
     table.Columns.Add(idColumn)
     table.Columns.Add(itemColumn)
     dataSet.Tables.Add(table)

     ' Set primary key column.
     keyColumn(0) = idColumn
     table.PrimaryKey = keyColumn

     ' Add ten rows.
     Dim i As Integer
     For i = 0 To 9
         row = table.NewRow()
         row("Item") = i
         table.Rows.Add(row)
     Next i

     ' Accept changes.
     dataSet.AcceptChanges()
     PrintValues(dataSet, "Original values")

     ' Change two row values.
     table.Rows(0)("Item") = 50
     table.Rows(1)("Item") = 111

     ' Add one row.
     row = table.NewRow()
     row("Item") = 74
     table.Rows.Add(row)

     ' Insert code for error checking. Set one row in error.
     table.Rows(1).RowError = "over 100"
     PrintValues(dataSet, "Modified and New Values")

     ' If the table has changes or errors, create a subset DataSet.
     If dataSet.HasChanges(DataRowState.Modified Or DataRowState.Added) _
        And dataSet.HasErrors Then

         ' Use GetChanges to extract subset.
         changeDataSet = dataSet.GetChanges(DataRowState.Modified _
            Or DataRowState.Added)
         PrintValues(changeDataSet, "Subset values")

         ' Insert code to reconcile errors. In this case, reject changes.
         Dim changeTable As DataTable
         For Each changeTable In  changeDataSet.Tables
             If changeTable.HasErrors Then
                 Dim changeRow As DataRow
                 For Each changeRow In  changeTable.Rows
                     'Console.WriteLine(changeRow["Item"]);
                     If CInt(changeRow("Item", _
                        DataRowVersion.Current)) > 100 Then
                         changeRow.RejectChanges()
                         changeRow.ClearErrors()
                     End If
                 Next changeRow
             End If
         Next changeTable
         PrintValues(changeDataSet, "Reconciled subset values")

         ' Merge changes back to first DataSet.
         dataSet.Merge(changeDataSet)
         PrintValues(dataSet, "Merged Values")
     End If
 End Sub
 
Private Sub PrintValues(dataSet As DataSet, label As String)
     Console.WriteLine(ControlChars.Cr & label)
     Dim table As DataTable
     For Each table In  dataSet.Tables
         Console.WriteLine("TableName: " & table.TableName)
         Dim row As DataRow
         For Each row In  table.Rows
             Dim column As DataColumn
             For Each column In  table.Columns
                 Console.Write(ControlChars.Tab & " " _
                    & row(column).ToString())
             Next column
             Console.WriteLine()
         Next row
     Next table
End Sub

注解

Merge 方法用于合并两个大体类似架构的 DataSet 对象。The Merge method is used to merge two DataSet objects that have largely similar schemas. 通常在客户端应用程序上使用合并,以将数据源中的最新更改合并到现有 DataSet中。A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. 这允许客户端应用程序使用数据源中的最新数据进行刷新 DataSetThis allows the client application to have a refreshed DataSet with the latest data from the data source.

通常在一系列过程的末尾调用 Merge 方法,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataSetThe Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

在客户端应用程序中,通常有一个按钮,用户可以单击该按钮来收集更改的数据并对其进行验证,然后再将其发送回中间层组件。In a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. 在此方案中,首先调用 GetChanges 方法。In this scenario, the GetChanges method is first invoked. 该方法将返回第二个针对验证和合并进行优化 DataSetThat method returns a second DataSet optimized for validating and merging. 此第二个 DataSet 对象只包含已更改的 DataTableDataRow 对象,导致原始 DataSet的子集。This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. 此子集通常较小,因此更有效地传递回中间层组件。This subset is generally smaller, and thus more efficiently passed back to a middle-tier component. 然后,中间层组件使用存储过程中的更改来更新原始数据源。The middle-tier component then updates the original data source with the changes through stored procedures. 然后,中间层可以发回包含原始数据的新 DataSet 和数据源中的最新数据(再次运行原始查询),也可以将其从数据源中所做的任何更改发送回。The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (例如,如果数据源自动创建唯一的主键值,则这些值可以传播回客户端应用程序。)在任一情况下,返回的 DataSet 都可以与 Merge 方法一起合并回客户端应用程序的原始 DataSet(For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

调用 Merge 方法时,将比较两个 DataSet 对象的架构,因为架构可能已更改。When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. 例如,在企业对企业方案中,可能已通过自动化过程将新列添加到了 XML 架构。For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. 如果源 DataSet 包含目标中缺少的架构元素(添加 DataColumn 对象),则可以通过将 missingSchemaAction 参数设置为 MissingSchemaAction.Add来将架构元素添加到目标。If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. 在这种情况下,合并的 DataSet 包含添加的架构和数据。In that case, the merged DataSet contains the added schema and data.

合并架构后,数据将合并。After merging schemas, the data is merged.

在将新的源 DataSet 合并到目标时,DataRowState 值为 UnchangedModifiedDeleted 的任何源行都将与具有相同的主键值的目标行匹配。When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. DataRowState 值为 Added 的源行与新源行的主键值相同的新目标行匹配。Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

在合并过程中,将禁用约束。During a merge, constraints are disabled. 如果在合并结束时无法启用任何约束,则会生成 ConstraintException,并在禁用约束时保留合并的数据。If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. 在这种情况下,EnforceConstraints 属性设置为 false,所有无效行都标记为 "错误"。In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. 在尝试将 EnforceConstraints 属性重置为 true之前,必须解决这些错误。The errors must be resolved before attempting to reset the EnforceConstraints property to true.

另请参阅

Merge(DataTable)

将指定的 DataTable 及其架构合并到当前 DataSet 中。Merges a specified DataTable and its schema into the current DataSet.

public:
 void Merge(System::Data::DataTable ^ table);
public void Merge (System.Data.DataTable table);
member this.Merge : System.Data.DataTable -> unit
Public Sub Merge (table As DataTable)

参数

table
DataTable

其数据和架构将被合并的 DataTableThe DataTable whose data and schema will be merged.

异常

tablenullThe table is null.

示例

下面的示例创建一个简单的 DataSet,其中包含一个表、两个列和10个行。The following example creates a simple DataSet with one table, two columns, and ten rows. 创建与第一个 DataTable 相同的第二个。A second DataTable is created that is identical to the first. 向第二个表添加两行,然后将其合并到 DataSet中。Two rows are added to the second table, which is then merged into the DataSet.

   private void DemonstrateMergeTable()
   {
       // Create a DataSet with one table, two columns, and ten rows.
       DataSet dataSet = new DataSet("dataSet");
       DataTable table = new DataTable("Items");

       // Add table to the DataSet
       dataSet.Tables.Add(table);

       // Add columns
       DataColumn c1 = new DataColumn("id", 
           Type.GetType("System.Int32"),"");
       DataColumn c2 = new DataColumn("Item", 
           Type.GetType("System.Int32"),"");
       table.Columns.Add(c1);
       table.Columns.Add(c2);

       // DataColumn array to set primary key.
       DataColumn[] keyCol= new DataColumn[1];

       // Set primary key column.
       keyCol[0]= c1;
       table.PrimaryKey=keyCol;

       // Add a RowChanged event handler for the table.
       table.RowChanged += new 
           DataRowChangeEventHandler(Row_Changed);

       // Add ten rows.
       for(int i = 0; i <10;i++)
       {
           DataRow row=table.NewRow();
           row["id"] = i;
           row["Item"]= i;
           table.Rows.Add(row);
       }
       // Accept changes.
       dataSet.AcceptChanges();

       PrintValues(dataSet, "Original values");

       // Create a second DataTable identical to the first.
       DataTable t2 = table.Clone();

       // Add three rows. Note that the id column can'te be the
       // same as existing rows in the DataSet table.
       DataRow newRow;
       newRow = t2.NewRow();
       newRow["id"] = 14;
       newRow["item"] = 774;

       //Note the alternative method for adding rows.
       t2.Rows.Add(new Object[] { 12, 555 });
       t2.Rows.Add(new Object[] { 13, 665 });

       // Merge the table into the DataSet
       Console.WriteLine("Merging");
       dataSet.Merge(t2);
       PrintValues(dataSet, "Merged With table.");
   }

   private void Row_Changed(object sender, 
       DataRowChangeEventArgs e)
   {
       Console.WriteLine("Row Changed " + e.Action.ToString() 
           + "\table" + e.Row.ItemArray[0]);
   }

   private void PrintValues(DataSet dataSet, string label)
   {
       Console.WriteLine("\n" + label);
       foreach(DataTable table in dataSet.Tables)
       {
           Console.WriteLine("TableName: " + table.TableName);
           foreach(DataRow row in table.Rows)
           {
               foreach(DataColumn column in table.Columns)
               {
                   Console.Write("\table " + row[column] );
               }
               Console.WriteLine();
           }
       }
   }
Private Sub DemonstrateMergeTable()
    ' Create a DataSet with one table, two columns, 
    ' and ten rows.
    Dim dataSet As New DataSet("dataSet")
    Dim table As New DataTable("Items")

    ' Add tables to the DataSet
    dataSet.Tables.Add(table)

    ' Add columns
    Dim c1 As New DataColumn("id", Type.GetType("System.Int32"), "")
    Dim c2 As New DataColumn("Item", Type.GetType("System.Int32"), "")
    table.Columns.Add(c1)
    table.Columns.Add(c2)

    ' DataColumn array to set primary key.
    Dim keyCol(0) As DataColumn

    ' Set primary key column.
    keyCol(0) = c1
    table.PrimaryKey = keyCol

    ' Add RowChanged event handler for the table.
    AddHandler table.RowChanged, AddressOf Row_Changed

    ' Add ten rows.
    Dim i As Integer
    Dim row As DataRow

    For i = 0 To 9
        row = table.NewRow()
        row("id") = i
        row("Item") = i
        table.Rows.Add(row)
    Next i

    ' Accept changes.
    dataSet.AcceptChanges()
    PrintValues(dataSet, "Original values")

    ' Create a second DataTable identical to the first.
    Dim t2 As DataTable
    t2 = table.Clone()

    ' Add three rows. Note that the id column can't be the 
    ' same as existing rows in the DataSet table.
    Dim newRow As DataRow
    newRow = t2.NewRow()
    newRow("id") = 14
    newRow("Item") = 774
    t2.Rows.Add(newRow)

    newRow = t2.NewRow()
    newRow("id") = 12
    newRow("Item") = 555
    t2.Rows.Add(newRow)

    newRow = t2.NewRow()
    newRow("id") = 13
    newRow("Item") = 665
    t2.Rows.Add(newRow)

    ' Merge the table into the DataSet.
    Console.WriteLine("Merging")
    dataSet.Merge(t2)
    PrintValues(dataSet, "Merged With Table")
 End Sub 
     
 Private Sub Row_Changed( _
    sender As Object, e As DataRowChangeEventArgs)
     Console.WriteLine("Row Changed " & e.Action.ToString() _
        & ControlChars.Tab & e.Row.ItemArray(0).ToString())
 End Sub
 
 Private Sub PrintValues(dataSet As DataSet, label As String)
     Console.WriteLine(ControlChars.Cr & label)
     Dim table As DataTable
     Dim row As DataRow
     Dim column As DataColumn
     For Each table In  dataSet.Tables
         Console.WriteLine("TableName: " & table.TableName) 
         For Each row In  table.Rows             
             For Each column In  table.Columns
                 Console.Write(ControlChars.Tab & " " _
                    & row(column).ToString())
             Next column
             Console.WriteLine()
         Next row
     Next table
 End Sub

注解

Merge 方法用于合并两个大体类似架构的 DataSet 对象。The Merge method is used to merge two DataSet objects that have largely similar schemas. 通常在客户端应用程序上使用合并,以将数据源中的最新更改合并到现有 DataSet中。A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. 这允许客户端应用程序使用数据源中的最新数据进行刷新 DataSetThis allows the client application to have a refreshed DataSet with the latest data from the data source.

通常在一系列过程的末尾调用 Merge 方法,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataSetThe Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

在客户端应用程序中,通常有一个按钮,用户可以单击该按钮来收集更改的数据并对其进行验证,然后再将其发送回中间层组件。In a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. 在此方案中,首先调用 GetChanges 方法。In this scenario, the GetChanges method is first invoked. 该方法将返回第二个针对验证和合并进行优化 DataSetThat method returns a second DataSet optimized for validating and merging. 此第二个 DataSet 对象只包含已更改的 DataTableDataRow 对象,导致原始 DataSet的子集。This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. 此子集通常较小,因此更有效地传递回中间层组件。This subset is generally smaller, and thus more efficiently passed back to a middle-tier component. 然后,中间层组件使用存储过程中的更改来更新原始数据源。The middle-tier component then updates the original data source with the changes through stored procedures. 然后,中间层可以发回包含原始数据的新 DataSet 和数据源中的最新数据(再次运行原始查询),也可以将其从数据源中所做的任何更改发送回。The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (例如,如果数据源自动创建唯一的主键值,则这些值可以传播回客户端应用程序。)在任一情况下,返回的 DataSet 都可以与 Merge 方法一起合并回客户端应用程序的原始 DataSet(For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

调用 Merge 方法时,将比较两个 DataSet 对象的架构,因为架构可能已更改。When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. 例如,在企业对企业方案中,可能已通过自动化过程将新列添加到了 XML 架构。For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. 如果源 DataSet 包含目标中缺少的架构元素(添加 DataColumn 对象),则可以通过将 missingSchemaAction 参数设置为 MissingSchemaAction.Add来将架构元素添加到目标。If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. 在这种情况下,合并的 DataSet 包含添加的架构和数据。In that case, the merged DataSet contains the added schema and data.

合并架构后,数据将合并。After merging schemas, the data is merged.

在将新的源 DataSet 合并到目标时,DataRowState 值为 UnchangedModifiedDeleted 的任何源行都将与具有相同的主键值的目标行匹配。When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. DataRowState 值为 Added 的源行与新源行的主键值相同的新目标行匹配。Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

在合并过程中,将禁用约束。During a merge, constraints are disabled. 如果在合并结束时无法启用任何约束,则会生成 ConstraintException,并在禁用约束时保留合并的数据。If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. 在这种情况下,EnforceConstraints 属性设置为 false,所有无效行都标记为 "错误"。In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. 在尝试将 EnforceConstraints 属性重置为 true之前,必须解决这些错误。The errors must be resolved before attempting to reset the EnforceConstraints property to true.

另请参阅

Merge(DataSet, Boolean)

将指定的 DataSet 及其架构合并到当前 DataSet 中,在此过程中,将根据给定的参数保留或放弃在此 DataSet 中进行的任何更改。Merges a specified DataSet and its schema into the current DataSet, preserving or discarding any changes in this DataSet according to the given argument.

public:
 void Merge(System::Data::DataSet ^ dataSet, bool preserveChanges);
public void Merge (System.Data.DataSet dataSet, bool preserveChanges);
member this.Merge : System.Data.DataSet * bool -> unit

参数

dataSet
DataSet

其数据和架构将被合并的 DataSetThe DataSet whose data and schema will be merged.

preserveChanges
Boolean

要保留当前 true 中的更改,则返回 DataSet;否则,返回 falsetrue to preserve changes in the current DataSet; otherwise, false.

示例

下面的示例创建一个简单的 DataSet,其中包含一个表、两个列和10个行。The following example creates a simple DataSet with one table, two columns, and ten rows. 添加10行后,将更改两个值,并添加一行。After adding ten rows, two values are changed, and one row is added. 更改后的数据的子集使用 GetChanges 方法创建。A subset of the changed data is created using the GetChanges method. 在协调错误后,将子集数据合并到原始 DataSetAfter reconciling errors, the subset data is merged into the original DataSet.

   private void DemonstrateMerge()
   {
       // Create a DataSet with one table, two columns, 
       // and three rows.
       DataSet dataSet = new DataSet("dataSet");
       DataTable table = new DataTable("Items");
       DataColumn idColumn = new DataColumn("id", 
           Type.GetType("System.Int32"),"");
       idColumn.AutoIncrement=true;
       DataColumn itemColumn = new DataColumn("Item", 
           Type.GetType("System.Int32"),"");

       // DataColumn array to set primary key.
       DataColumn[] keyColumn= new DataColumn[1];
       DataRow row;

       // Create variable for temporary DataSet. 
       DataSet changesDataSet;

       // Add RowChanged event handler for the table.
       table.RowChanged+=new DataRowChangeEventHandler(
           Row_Changed);
       dataSet.Tables.Add(table);
       table.Columns.Add(idColumn);
       table.Columns.Add(itemColumn);

       // Set primary key column.
       keyColumn[0]= idColumn;
       table.PrimaryKey=keyColumn;
       // Add ten rows.
       for(int i = 0; i <10;i++)
       {
           row=table.NewRow();
           row["Item"]= i;
           table.Rows.Add(row);
       }
       // Accept changes.
       dataSet.AcceptChanges();
       PrintValues(dataSet, "Original values");

       // Change row values.
       table.Rows[0]["Item"]= 50;
       table.Rows[1]["Item"]= 111;

       // Add one row.
       row=table.NewRow();
       row["Item"]=74;
       table.Rows.Add(row);

       // Insert code for error checking. Set one row in error.
       table.Rows[1].RowError= "over 100";
       PrintValues(dataSet, "Modified and New Values");

       // If the table has changes or errors, 
       // create a subset DataSet.
       if(dataSet.HasChanges(DataRowState.Modified | 
           DataRowState.Added)&& dataSet.HasErrors)
       {
           // Use GetChanges to extract subset.
           changesDataSet = dataSet.GetChanges(
               DataRowState.Modified|DataRowState.Added);
           PrintValues(changesDataSet, "Subset values");

           // Insert code to reconcile errors. In this case, reject changes.
           foreach(DataTable changesTable in changesDataSet.Tables)
           {
               if (changesTable.HasErrors)
               {
                   foreach(DataRow changesRow in changesTable.Rows)
                   {
                       //Console.WriteLine(changesRow["Item"]);
                       if((int)changesRow["Item",DataRowVersion.Current ]> 100)
                       {
                           changesRow.RejectChanges();
                           changesRow.ClearErrors();
                       }
                   }
               }
           }
           // Add a column to the changesDataSet.
           changesDataSet.Tables["Items"].Columns.Add(
               new DataColumn("newColumn"));
           PrintValues(changesDataSet, "Reconciled subset values");
           // Merge changes back to first DataSet.
           dataSet.Merge(changesDataSet, false, 
               System.Data.MissingSchemaAction.Add);
       }
       PrintValues(dataSet, "Merged Values");
   }

   private void Row_Changed(object sender, DataRowChangeEventArgs e)
   {
       Console.WriteLine("Row Changed " + e.Action.ToString() 
           + "\table" + e.Row.ItemArray[0]);
   }

   private void PrintValues(DataSet dataSet, string label)
   {
       Console.WriteLine(label + "\n");
       foreach(DataTable table in dataSet.Tables)
       {
           Console.WriteLine("TableName: " + table.TableName);
           foreach(DataRow row in table.Rows)
           {
               foreach(DataColumn column in table.Columns)
               {
                   Console.Write("\table " + row[column] );
               }
               Console.WriteLine();
           }
       }
   }
Private Sub DemonstrateMerge()
    ' Create a DataSet with one table, two columns, 
    ' and three rows.
    Dim dataSet As New DataSet("dataSet")
    Dim table As New DataTable("Items")
    Dim idColumn As New DataColumn("id", _
        Type.GetType("System.Int32"), "")
    idColumn.AutoIncrement = True
    Dim itemColumn As New DataColumn("Item", _
        Type.GetType("System.Int32"), "")

    ' Create DataColumn array to set primary key.
    Dim keyColumn(0) As DataColumn
    Dim row As DataRow

    ' Create variable for temporary DataSet. 
    Dim changesDataSet As DataSet

    ' Add RowChanged event handler for the table.
    AddHandler table.RowChanged, AddressOf Row_Changed
    dataSet.Tables.Add(table)
    table.Columns.Add(idColumn)
    table.Columns.Add(itemColumn)

    ' Set primary key column.
    keyColumn(0) = idColumn
    table.PrimaryKey = keyColumn

    ' Add ten rows.
    Dim i As Integer
    For i = 0 To 9
        row = table.NewRow()
        row("Item") = i
        table.Rows.Add(row)
    Next i

    ' Accept changes.
    dataSet.AcceptChanges()
    PrintValues(dataSet, "Original values")

    ' Change row values.
    table.Rows(0)("Item") = 50
    table.Rows(1)("Item") = 111

    ' Add one row.
    row = table.NewRow()
    row("Item") = 74
    table.Rows.Add(row)

    ' Insert code for error checking. Set one row in error.
    table.Rows(1).RowError = "over 100"
    PrintValues(dataSet, "Modified and New Values")

    ' If the table has changes or errors, create a subset DataSet.
    If dataSet.HasChanges(DataRowState.Modified Or DataRowState.Added) _
        And dataSet.HasErrors Then
        ' Use GetChanges to extract subset.
        changesDataSet = dataSet.GetChanges( _
            DataRowState.Modified Or DataRowState.Added)
        PrintValues(changesDataSet, "Subset values")

        ' Insert code to reconcile errors. In this case, reject changes.
        Dim changesTable As DataTable
        For Each changesTable In  changesDataSet.Tables
            If changesTable.HasErrors Then
                Dim changesRow As DataRow
                For Each changesRow In  changesTable.Rows
                    'Console.WriteLine(changesRow["Item"]);
                    If CInt(changesRow("Item", _
                        DataRowVersion.Current)) > 100 Then
                        changesRow.RejectChanges()
                        changesRow.ClearErrors()
                    End If
                Next changesRow
            End If
        Next changesTable

        ' Add a column to the changesDataSet.
        changesDataSet.Tables("Items").Columns.Add( _
            New DataColumn("newColumn"))
        PrintValues(changesDataSet, "Reconciled subset values")

        ' Merge changes back to first DataSet.
        dataSet.Merge(changesDataSet, False, _
            System.Data.MissingSchemaAction.Add)
    End If
    PrintValues(dataSet, "Merged Values")
End Sub
        
 Private Sub Row_Changed(sender As Object, e As DataRowChangeEventArgs)
     Console.WriteLine("Row Changed " + e.Action.ToString() _
        + ControlChars.Tab + e.Row.ItemArray(0).ToString())
 End Sub
    
Private Sub PrintValues(dataSet As DataSet, label As String)
     Console.WriteLine(label + ControlChars.Cr)
     Dim table As DataTable
     For Each table In  dataSet.Tables
         Console.WriteLine("TableName: " + table.TableName)
         Dim row As DataRow
         For Each row In  table.Rows
             Dim column As DataColumn
             For Each column In  table.Columns
                 Console.Write(ControlChars.Tab & " " _
                    & row(column).ToString())
             Next column
             Console.WriteLine()
         Next row
     Next table
End Sub

注解

Merge 方法用于合并两个大体类似架构的 DataSet 对象。The Merge method is used to merge two DataSet objects that have largely similar schemas. 通常在客户端应用程序上使用合并,以将数据源中的最新更改合并到现有 DataSet中。A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. 这允许客户端应用程序使用数据源中的最新数据进行刷新 DataSetThis allows the client application to have a refreshed DataSet with the latest data from the data source.

通常在一系列过程的末尾调用 Merge 方法,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataSetThe Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

在客户端应用程序中,通常有一个按钮,用户可以单击该按钮来收集更改的数据并对其进行验证,然后再将其发送回中间层组件。In a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. 在此方案中,首先调用 GetChanges 方法。In this scenario, the GetChanges method is first invoked. 该方法将返回第二个针对验证和合并进行优化 DataSetThat method returns a second DataSet optimized for validating and merging. 此第二个 DataSet 对象只包含已更改的 DataTableDataRow 对象,导致原始 DataSet的子集。This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. 此子集通常较小,因此更有效地传递回中间层组件。This subset is generally smaller, and thus more efficiently passed back to a middle-tier component. 然后,中间层组件使用存储过程中的更改来更新原始数据源。The middle-tier component then updates the original data source with the changes through stored procedures. 然后,中间层可以发回包含原始数据的新 DataSet 和数据源中的最新数据(再次运行原始查询),也可以将其从数据源中所做的任何更改发送回。The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (例如,如果数据源自动创建唯一的主键值,则这些值可以传播回客户端应用程序。)在任一情况下,返回的 DataSet 都可以与 Merge 方法一起合并回客户端应用程序的原始 DataSet(For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

调用 Merge 方法时,将比较两个 DataSet 对象的架构,因为架构可能已更改。When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. 例如,在企业对企业方案中,可能已通过自动化过程将新列添加到了 XML 架构。For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. 如果源 DataSet 包含目标中缺少的架构元素(添加 DataColumn 对象),则可以通过将 missingSchemaAction 参数设置为 MissingSchemaAction.Add来将架构元素添加到目标。If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. 在这种情况下,合并的 DataSet 包含添加的架构和数据。In that case, the merged DataSet contains the added schema and data.

合并架构后,数据将合并。After merging schemas, the data is merged.

在将新的源 DataSet 合并到目标时,DataRowState 值为 UnchangedModifiedDeleted 的任何源行都将与具有相同的主键值的目标行匹配。When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. DataRowState 值为 Added 的源行与新源行的主键值相同的新目标行匹配。Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

在合并过程中,将禁用约束。During a merge, constraints are disabled. 如果在合并结束时无法启用任何约束,则会生成 ConstraintException,并在禁用约束时保留合并的数据。If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. 在这种情况下,EnforceConstraints 属性设置为 false,所有无效行都标记为 "错误"。In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. 在尝试将 EnforceConstraints 属性重置为 true之前,必须解决这些错误。The errors must be resolved before attempting to reset the EnforceConstraints property to true.

另请参阅

Merge(DataRow[], Boolean, MissingSchemaAction)

DataRow 对象数组合并到当前的 DataSet 中,在此过程中,将根据给定的参数保留或放弃在 DataSet 中进行的更改并处理不兼容的架构。Merges an array of DataRow objects into the current DataSet, preserving or discarding changes in the DataSet and handling an incompatible schema according to the given arguments.

public:
 void Merge(cli::array <System::Data::DataRow ^> ^ rows, bool preserveChanges, System::Data::MissingSchemaAction missingSchemaAction);
public void Merge (System.Data.DataRow[] rows, bool preserveChanges, System.Data.MissingSchemaAction missingSchemaAction);
member this.Merge : System.Data.DataRow[] * bool * System.Data.MissingSchemaAction -> unit

参数

rows
DataRow[]

要合并到 DataRow 中的 DataSet 对象数组。The array of DataRow objects to be merged into the DataSet.

preserveChanges
Boolean

要保留 true 中的更改,则返回 DataSet;否则,返回 falsetrue to preserve changes in the DataSet; otherwise, false.

missingSchemaAction
MissingSchemaAction

MissingSchemaAction 值之一。One of the MissingSchemaAction values.

注解

Merge 方法用于合并两个大体类似架构的 DataSet 对象。The Merge method is used to merge two DataSet objects that have largely similar schemas. 通常在客户端应用程序上使用合并,以将数据源中的最新更改合并到现有 DataSet中。A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. 这允许客户端应用程序使用数据源中的最新数据进行刷新 DataSetThis allows the client application to have a refreshed DataSet with the latest data from the data source.

通常在一系列过程的末尾调用 Merge 方法,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataSetThe Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

在客户端应用程序中,通常有一个按钮,用户可以单击该按钮来收集更改的数据并对其进行验证,然后再将其发送回中间层组件。In a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. 在此方案中,首先调用 GetChanges 方法。In this scenario, the GetChanges method is first invoked. 该方法将返回第二个针对验证和合并进行优化 DataSetThat method returns a second DataSet optimized for validating and merging. 此第二个 DataSet 对象只包含已更改的 DataTableDataRow 对象,导致原始 DataSet的子集。This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. 此子集通常较小,因此更有效地传递回中间层组件。This subset is generally smaller, and thus more efficiently passed back to a middle-tier component. 然后,中间层组件使用存储过程中的更改来更新原始数据源。The middle-tier component then updates the original data source with the changes through stored procedures. 然后,中间层可以发回包含原始数据的新 DataSet 和数据源中的最新数据(再次运行原始查询),也可以将其从数据源中所做的任何更改发送回。The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (例如,如果数据源自动创建唯一的主键值,则这些值可以传播回客户端应用程序。)在任一情况下,返回的 DataSet 都可以与 Merge 方法一起合并回客户端应用程序的原始 DataSet(For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

为了便于说明 Merge 方法,我们使用 "目标" 来表示当前 DataSet,并使用 "source" 将第二个(参数) DataSet命名为。To facilitate explanation of the Merge method, we use "target" to signify the current DataSet, and "source" to name the second (parameter) DataSet. 由于目标 DataSet 为,因此将其命名为,因为它是发生操作(合并)的对象。The target DataSet is so named because it is the object upon which an action (the merge) occurs. 第二个 DataSet 称为 "源",因为它包含的信息不会更改,而是合并到当前的 DataSet中。The second DataSet is called a "source" because the information it contains does not change, but instead is merged into the current DataSet.

调用 Merge 方法时,将比较两个 DataSet 对象的架构,因为架构可能已更改。When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. 例如,在企业对企业方案中,可能已通过自动化过程将新列添加到了 XML 架构。For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. 如果源 DataSet 包含目标中缺少的架构元素(添加 DataColumn 对象),则可以通过将 missingSchemaAction 参数设置为 MissingSchemaAction.Add来将架构元素添加到目标。If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. 在这种情况下,合并的 DataSet 包含添加的架构和数据。In that case, the merged DataSet contains the added schema and data.

合并架构后,数据将合并。After merging schemas, the data is merged.

在将新的源 DataSet 合并到目标时,DataRowState 值为 UnchangedModifiedDeleted 的任何源行都将与具有相同的主键值的目标行匹配。When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. DataRowState 值为 Added 的源行与新源行的主键值相同的新目标行匹配。Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

在合并过程中,将禁用约束。During a merge, constraints are disabled. 如果在合并结束时无法启用任何约束,则会生成 ConstraintException,并在禁用约束时保留合并的数据。If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. 在这种情况下,EnforceConstraints 属性设置为 false,所有无效行都标记为 "错误"。In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. 在尝试将 EnforceConstraints 属性重置为 true之前,必须解决这些错误。The errors must be resolved before attempting to reset the EnforceConstraints property to true.

另请参阅

Merge(DataSet, Boolean, MissingSchemaAction)

将指定的 DataSet 及其架构与当前的 DataSet 合并,在此过程中,将根据给定的参数保留或放弃在当前 DataSet 中的更改并处理不兼容的架构。Merges a specified DataSet and its schema with the current DataSet, preserving or discarding changes in the current DataSet and handling an incompatible schema according to the given arguments.

public:
 void Merge(System::Data::DataSet ^ dataSet, bool preserveChanges, System::Data::MissingSchemaAction missingSchemaAction);
public void Merge (System.Data.DataSet dataSet, bool preserveChanges, System.Data.MissingSchemaAction missingSchemaAction);
member this.Merge : System.Data.DataSet * bool * System.Data.MissingSchemaAction -> unit

参数

dataSet
DataSet

其数据和架构将被合并的 DataSetThe DataSet whose data and schema will be merged.

preserveChanges
Boolean

要保留当前 true 中的更改,则返回 DataSet;否则,返回 falsetrue to preserve changes in the current DataSet; otherwise, false.

missingSchemaAction
MissingSchemaAction

MissingSchemaAction 值之一。One of the MissingSchemaAction values.

异常

dataSetnullThe dataSet is null.

示例

下面的示例创建一个简单的 DataSet,其中包含一个表、两个列和10个行。The following example creates a simple DataSet with one table, two columns, and ten rows. 更改了两个值,并添加了一行。Two values are changed, and one row is added. 更改后的数据的子集使用 GetChanges 方法创建。A subset of the changed data is created using the GetChanges method. 在协调错误后,会将一个新列添加到子集,从而更改架构。After reconciling errors, a new column is added to the subset, changing the schema. 当调用 Merge 方法时,如果将 missingSchemaAction 设置为 MissingSchemaAction.Add,则新列将添加到原始 DataSet 对象的架构。When the Merge method is called with the missingSchemaAction set to MissingSchemaAction.Add, the new column is added to the original DataSet object's schema.

   private void DemonstrateMergeMissingSchema()
   {
       // Create a DataSet with one table, two columns, 
       // and three rows.
       DataSet dataSet = new DataSet("dataSet");
       DataTable table = new DataTable("Items");
       DataColumn idColumn = new DataColumn("id", 
           Type.GetType("System.Int32"));
       idColumn.AutoIncrement=true;
       DataColumn itemColumn = new DataColumn("Item", 
           Type.GetType("System.Int32"));
       // DataColumn array to set primary key.

       DataColumn[] keyColumn= new DataColumn[1];
       DataRow row;
       // Create variable for temporary DataSet. 
       DataSet changeDataSet;

       // Add RowChanged event handler for the table.
       table.RowChanged+= new DataRowChangeEventHandler(
           Row_Changed);
       dataSet.Tables.Add(table);
       table.Columns.Add(idColumn);
       table.Columns.Add(itemColumn);

       // Set primary key column.
       keyColumn[0]= idColumn;
       table.PrimaryKey=keyColumn;

       // Add ten rows.
       for(int i = 0; i <10;i++)
       {
           row=table.NewRow();
           row["Item"]= i;
           table.Rows.Add(row);
       }

       // Accept changes.
       dataSet.AcceptChanges();
       PrintValues(dataSet, "Original values");

       // Change row values.
       table.Rows[0]["Item"]= 50;
       table.Rows[1]["Item"]= 111;

       // Add one row.
       row=table.NewRow();
       row["Item"]=74;
       table.Rows.Add(row);

       // Insert code for error checking. Set one row in error.
       table.Rows[1].RowError= "over 100";
       PrintValues(dataSet, "Modified and New Values");
       // If the table has changes or errors, create a subset DataSet.
       if(dataSet.HasChanges(DataRowState.Modified | 
           DataRowState.Added)& dataSet.HasErrors)
       {
           // Use GetChanges to extract subset.
           changeDataSet = dataSet.GetChanges(
               DataRowState.Modified|DataRowState.Added);
           PrintValues(changeDataSet, "Subset values");

           // Insert code to reconcile errors. Reject the changes.
           foreach(DataTable changeTable in changeDataSet.Tables)
           {
               if (changeTable.HasErrors)
               {
                   foreach(DataRow changeRow in changeTable.Rows)
                   {
                       //Console.WriteLine(changeRow["Item"]);
                       if((int)changeRow["Item", 
                           DataRowVersion.Current ]> 100)
                       {
                           changeRow.RejectChanges();
                           changeRow.ClearErrors();
                       }
                   }
               }
           }
           // Add a column to the changeDataSet to change the schema.
           changeDataSet.Tables["Items"].Columns.Add(
               new DataColumn("newColumn"));
           PrintValues(changeDataSet, "Reconciled subset values");

           // Add values to the rows for each column.
           foreach(DataRow rowItem in changeDataSet.Tables["Items"].Rows)
           {
               rowItem["newColumn"] = "my new schema value";
           }
           // Merge changes back to first DataSet.
           dataSet.Merge(changeDataSet, false,
               System.Data.MissingSchemaAction.Add);
       }
       PrintValues(dataSet, "Merged Values");
   }

   private void Row_Changed(object sender, DataRowChangeEventArgs e)
   {
       Console.WriteLine("Row Changed " + e.Action.ToString() 
           + "\table" + e.Row.ItemArray[0]);
   }

   private void PrintValues(DataSet dataSet, string label)
   {
       Console.WriteLine("\n" + label);
       foreach(DataTable table in dataSet.Tables)
       {
           Console.WriteLine("TableName: " + table.TableName);
           foreach(DataRow row in table.Rows)
           {
               foreach(DataColumn column in table.Columns)
               {
                   Console.Write("\table " + row[column] );
               }
               Console.WriteLine();
           }
       }
   }
Private Sub DemonstrateMergeMissingSchema()
    ' Create a DataSet with one table, two columns, 
    ' and three rows.
    Dim dataSet As New DataSet("dataSet")
    Dim table As New DataTable("Items")
    Dim idColumn As New DataColumn("id", _
        Type.GetType("System.Int32"))
    idColumn.AutoIncrement = True
    Dim itemColumn As New DataColumn("Item", _
        Type.GetType("System.Int32"))

    ' DataColumn array to set primary key.
    Dim keyColumn(0) As DataColumn
    Dim row As DataRow

    ' Create variable for temporary DataSet. 
    Dim changeDataSet As DataSet

    ' Add RowChanged event handler for the table.
    AddHandler table.RowChanged, AddressOf Row_Changed
    dataSet.Tables.Add(table)
    table.Columns.Add(idColumn)
    table.Columns.Add(itemColumn)

    ' Set primary key column.
    keyColumn(0) = idColumn
    table.PrimaryKey = keyColumn

    ' Add ten rows.
    Dim i As Integer
    For i = 0 To 9
        row = table.NewRow()
        row("Item") = i
        table.Rows.Add(row)
    Next i

    ' Accept changes.
    dataSet.AcceptChanges()
    PrintValues(dataSet, "Original values")

    ' Change row values.
    table.Rows(0)("Item") = 50
    table.Rows(1)("Item") = 111

    ' Add one row.
    row = table.NewRow()
    row("Item") = 74
    table.Rows.Add(row)

    ' Insert code for error checking. Set one row in error.
    table.Rows(1).RowError = "over 100"
    PrintValues(dataSet, "Modified and New Values")
    ' If the table has changes or errors, 
    ' create a subset DataSet.
    If dataSet.HasChanges(DataRowState.Modified Or DataRowState.Added) _
        And dataSet.HasErrors Then
        ' Use GetChanges to extract subset.
        changeDataSet = dataSet.GetChanges(DataRowState.Modified _
            Or DataRowState.Added)
        PrintValues(changeDataSet, "Subset values")
        ' Insert code to reconcile errors. In this case, reject changes.
        Dim changeTable As DataTable
        For Each changeTable In  changeDataSet.Tables
            If changeTable.HasErrors Then
                Dim changeRow As DataRow
                For Each changeRow In  changeTable.Rows
                    If CInt(changeRow("Item", _
                        DataRowVersion.Current)) > 100 Then
                        changeRow.RejectChanges()
                        changeRow.ClearErrors()
                    End If
                Next changeRow
            End If
        Next changeTable

        ' Add a column to the changeDataSet to change the schema.
        changeDataSet.Tables("Items").Columns.Add( _
            New DataColumn("newColumn"))
        PrintValues(changeDataSet, "Reconciled subset values")

        ' Add values to the rows for each column.
        Dim rowItem As DataRow
        For Each rowItem In  changeDataSet.Tables("Items").Rows
            rowItem("newColumn") = "my new schema value"
        Next rowItem

        ' Merge changes back to first DataSet.
        dataSet.Merge(changeDataSet, False, _
            System.Data.MissingSchemaAction.Add)
    End If
    PrintValues(dataSet, "Merged Values")
End Sub
    
Private Sub Row_Changed(sender As Object, _
    e As DataRowChangeEventArgs)
     Console.WriteLine("Row Changed " & e.Action.ToString() _
        & ControlChars.Tab & e.Row.ItemArray(0).ToString())
End Sub
 
Private Sub PrintValues(dataSet As DataSet, label As String)
    Console.WriteLine(ControlChars.Cr & label)
    Dim table As DataTable
    For Each table In  dataSet.Tables
        Console.WriteLine("TableName: " & table.TableName)
        Dim row As DataRow
        For Each row In  table.Rows
            Dim column As DataColumn
            For Each column In  table.Columns
                Console.Write(ControlChars.Tab & " " _
                    & row(column).ToString())
            Next column
            Console.WriteLine()
        Next row
    Next table
End Sub

注解

Merge 方法用于合并两个大体类似架构的 DataSet 对象。The Merge method is used to merge two DataSet objects that have largely similar schemas. 通常在客户端应用程序上使用合并,以将数据源中的最新更改合并到现有 DataSet中。A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. 这允许客户端应用程序使用数据源中的最新数据进行刷新 DataSetThis allows the client application to have a refreshed DataSet with the latest data from the data source.

通常在一系列过程的末尾调用 Merge 方法,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataSetThe Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

在客户端应用程序中,通常有一个按钮,用户可以单击该按钮来收集更改的数据并对其进行验证,然后再将其发送回中间层组件。In a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. 在此方案中,首先调用 GetChanges 方法。In this scenario, the GetChanges method is first invoked. 该方法将返回第二个针对验证和合并进行优化 DataSetThat method returns a second DataSet optimized for validating and merging. 此第二个 DataSet 对象只包含已更改的 DataTableDataRow 对象,导致原始 DataSet的子集。This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. 此子集通常较小,因此更有效地传递回中间层组件。This subset is generally smaller, and thus more efficiently passed back to a middle-tier component. 然后,中间层组件使用存储过程中的更改来更新原始数据源。The middle-tier component then updates the original data source with the changes through stored procedures. 然后,中间层可以发回包含原始数据的新 DataSet 和数据源中的最新数据(再次运行原始查询),也可以将其从数据源中所做的任何更改发送回。The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (例如,如果数据源自动创建唯一的主键值,则这些值可以传播回客户端应用程序。)在任一情况下,返回的 DataSet 都可以与 Merge 方法一起合并回客户端应用程序的原始 DataSet(For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

为了便于说明 Merge 方法,我们使用 "目标" 来表示当前 DataSet,并使用 "source" 将第二个(参数) DataSet命名为。To facilitate explanation of the Merge method, we use "target" to signify the current DataSet, and "source" to name the second (parameter) DataSet. 由于目标 DataSet 为,因此将其命名为,因为它是发生操作(合并)的对象。The target DataSet is so named because it is the object upon which an action (the merge) occurs. 第二个 DataSet 称为 "源",因为它包含的信息不会更改,而是合并到当前的 DataSet中。The second DataSet is called a "source" because the information it contains does not change, but instead is merged into the current DataSet.

调用 Merge 方法时,将比较两个 DataSet 对象的架构,因为架构可能已更改。When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. 例如,在企业对企业方案中,可能已通过自动化过程将新列添加到了 XML 架构。For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. 如果源 DataSet 包含目标中缺少的架构元素(添加 DataColumn 对象),则可以通过将 missingSchemaAction 参数设置为 MissingSchemaAction.Add来将架构元素添加到目标。If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. 在这种情况下,合并的 DataSet 包含添加的架构和数据。In that case, the merged DataSet contains the added schema and data.

合并架构后,数据将合并。After merging schemas, the data is merged.

在将新的源 DataSet 合并到目标时,DataRowState 值为 UnchangedModifiedDeleted 的任何源行都将与具有相同的主键值的目标行匹配。When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. DataRowState 值为 Added 的源行与新源行的主键值相同的新目标行匹配。Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

在合并过程中,将禁用约束。During a merge, constraints are disabled. 如果在合并结束时无法启用任何约束,则会生成 ConstraintException,并在禁用约束时保留合并的数据。If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. 在这种情况下,EnforceConstraints 属性设置为 false,所有无效行都标记为 "错误"。In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. 在尝试将 EnforceConstraints 属性重置为 true之前,必须解决这些错误。The errors must be resolved before attempting to reset the EnforceConstraints property to true.

另请参阅

Merge(DataTable, Boolean, MissingSchemaAction)

将指定的 DataTable 及其架构合并到当前的 DataSet 中,在此过程中,将根据给定的参数保留或放弃在 DataSet 中进行的更改并处理不兼容的架构。Merges a specified DataTable and its schema into the current DataSet, preserving or discarding changes in the DataSet and handling an incompatible schema according to the given arguments.

public:
 void Merge(System::Data::DataTable ^ table, bool preserveChanges, System::Data::MissingSchemaAction missingSchemaAction);
public void Merge (System.Data.DataTable table, bool preserveChanges, System.Data.MissingSchemaAction missingSchemaAction);
member this.Merge : System.Data.DataTable * bool * System.Data.MissingSchemaAction -> unit

参数

table
DataTable

其数据和架构将被合并的 DataTableThe DataTable whose data and schema will be merged.

preserveChanges
Boolean

MissingSchemaAction 值之一。One of the MissingSchemaAction values.

missingSchemaAction
MissingSchemaAction

要保留 true 中的更改,则返回 DataSet;否则,返回 falsetrue to preserve changes in the DataSet; otherwise, false.

异常

dataSetnullThe dataSet is null.

示例

下面的示例创建一个简单的 DataSet,其中包含一个表、两个列和10个行。The following example creates a simple DataSet with one table, two columns, and ten rows. 创建的第二个 DataTable 与第一个相同,不同之处在于向表中添加了新的 DataColumnA second DataTable is created that is nearly identical to the first except that a new DataColumn is added to the table. 向第二个表添加两行,然后将其合并到 DataSet,并将 preserveChanges 参数设置为 false,并将 missingSchemaAction 参数设置为 MissingSchemaAction.AddTwo rows are added to the second table, which is then merged into the DataSet with the preserveChanges argument set to false, and the missingSchemaAction argument set to MissingSchemaAction.Add.

   private void DemonstrateMergeTableAddSchema()
   {
       // Create a DataSet with one table, two columns, and ten rows.
       DataSet dataSet = new DataSet("dataSet");
       DataTable table = new DataTable("Items");

       // Add table to the DataSet
       dataSet.Tables.Add(table);

       // Create and add two columns to the DataTable
       DataColumn idColumn = new DataColumn("id", 
           Type.GetType("System.Int32"),"");
       idColumn.AutoIncrement=true;
       DataColumn itemColumn = new DataColumn("Item", 
           Type.GetType("System.Int32"),"");
       table.Columns.Add(idColumn);
       table.Columns.Add(itemColumn);

       // Set the primary key to the first column.
       table.PrimaryKey = new DataColumn[1]{ idColumn };

       // Add RowChanged event handler for the table.
       table.RowChanged+= new DataRowChangeEventHandler(Row_Changed);

       // Add ten rows.
       for(int i = 0; i <10;i++)
       {
           DataRow row=table.NewRow();
           row["Item"]= i;
           table.Rows.Add(row);
       }

       // Accept changes.
       dataSet.AcceptChanges();
       PrintValues(dataSet, "Original values");

       // Create a second DataTable identical to the first, with
       // one extra column using the Clone method.
       DataTable cloneTable = table.Clone();
       cloneTable.Columns.Add("extra", typeof(string));

       // Add two rows. Note that the id column can'table be the 
       // same as existing rows in the DataSet table.
       DataRow newRow;
       newRow=cloneTable.NewRow();
       newRow["id"]= 12;
       newRow["Item"]=555;
       newRow["extra"]= "extra Column 1";
       cloneTable.Rows.Add(newRow);

       newRow=cloneTable.NewRow();
       newRow["id"]= 13;
       newRow["Item"]=665;
       newRow["extra"]= "extra Column 2";
       cloneTable.Rows.Add(newRow);

       // Merge the table into the DataSet.
       Console.WriteLine("Merging");
       dataSet.Merge(cloneTable,false,MissingSchemaAction.Add);
       PrintValues(dataSet, "Merged With Table, Schema Added");
   }

   private void Row_Changed(object sender, 
       DataRowChangeEventArgs e)
   {
       Console.WriteLine("Row Changed " + e.Action.ToString() 
           + "\table" + e.Row.ItemArray[0]);
   }

   private void PrintValues(DataSet dataSet, string label)
   {
       Console.WriteLine("\n" + label);
       foreach(DataTable table in dataSet.Tables)
       {
           Console.WriteLine("TableName: " + table.TableName);
           foreach(DataRow row in table.Rows)
           {
               foreach(DataColumn column in table.Columns)
               {
                   Console.Write("\table " + row[column] );
               }
               Console.WriteLine();
           }
       }
   }
Private Sub DemonstrateMergeTableAddSchema()
    ' Create a DataSet with one table, two columns, 
    'and ten rows.
    Dim dataSet As New DataSet("dataSet")
    Dim table As New DataTable("Items")

    ' Add tables to the DataSet
    dataSet.Tables.Add(table)

    ' Create and add two columns to the DataTable
    Dim idColumn As New DataColumn("id", _
        Type.GetType("System.Int32"), "")
    idColumn.AutoIncrement = True
    Dim itemColumn As New DataColumn("Item", _
        Type.GetType("System.Int32"), "")
    table.Columns.Add(idColumn)
    table.Columns.Add(itemColumn)

    ' DataColumn array to set primary key.
    Dim keyCol(0) As DataColumn

    ' Set primary key column.
    keyCol(0) = idColumn
    table.PrimaryKey = keyCol

    ' Add RowChanged event handler for the table.
    AddHandler table.RowChanged, AddressOf Row_Changed

    ' Add ten rows.
    Dim i As Integer
    Dim row As DataRow

    For i = 0 To 9
        row = table.NewRow()
        row("Item") = i
        table.Rows.Add(row)
    Next i

    ' Accept changes.
    dataSet.AcceptChanges()
    PrintValues(dataSet, "Original values")

    ' Create a second DataTable identical to the first
    ' with one extra column using the Clone method.
    Dim cloneTable As New DataTable
    cloneTable = table.Clone()

    ' Add column.
    cloneTable.Columns.Add("extra", _
        Type.GetType("System.String"))

    ' Add two rows. Note that the id column can't be the 
    ' same as existing rows in the DataSet table.
    Dim newRow As DataRow
    newRow = cloneTable.NewRow()
    newRow("id") = 12
    newRow("Item") = 555
    newRow("extra") = "extra Column 1"
    cloneTable.Rows.Add(newRow)
        
    newRow = cloneTable.NewRow()
    newRow("id") = 13
    newRow("Item") = 665
    newRow("extra") = "extra Column 2"
    cloneTable.Rows.Add(newRow)

    ' Merge the table into the DataSet.
    Console.WriteLine("Merging")
    dataSet.Merge(cloneTable, False, MissingSchemaAction.Add)
    PrintValues(dataSet, "Merged With Table, Schema Added")
End Sub
  
Private Sub Row_Changed(sender As Object, _
    e As DataRowChangeEventArgs)
    Console.WriteLine("Row Changed " & e.Action.ToString() _
        & ControlChars.Tab & e.Row.ItemArray(0).ToString())
End Sub
    
Private Sub PrintValues(dataSet As DataSet, label As String)
    Console.WriteLine(ControlChars.Cr & label)
    Dim table As DataTable
    Dim row As DataRow
    Dim column As DataColumn
    For Each table In  dataSet.Tables
        Console.WriteLine("TableName: " & table.TableName)
        For Each row In  table.Rows             
            For Each column In  table.Columns
                Console.Write(ControlChars.Tab & " " _
                    & row(column).ToString())
            Next column
            Console.WriteLine()
        Next row
    Next table
 End Sub

注解

Merge 方法用于合并两个大体类似架构的 DataSet 对象。The Merge method is used to merge two DataSet objects that have largely similar schemas. 通常在客户端应用程序上使用合并,以将数据源中的最新更改合并到现有 DataSet中。A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. 这允许客户端应用程序使用数据源中的最新数据进行刷新 DataSetThis allows the client application to have a refreshed DataSet with the latest data from the data source.

通常在一系列过程的末尾调用 Merge 方法,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataSetThe Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

对于客户端应用程序,通常有一个按钮,用户可以单击该按钮来收集更改的数据并对其进行验证,然后再将其发送回中间层组件。iOn a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. 在此方案中,首先调用 GetChanges 方法。In this scenario, the GetChanges method is first invoked. 该方法将返回第二个针对验证和合并进行优化 DataSetThat method returns a second DataSet optimized for validating and merging. 此第二个 DataSet 对象只包含已更改的 DataTableDataRow 对象,导致原始 DataSet的子集。This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. 此子集通常较小,因此更有效地传递回中间层组件。This subset is generally smaller, and thus more efficiently passed back to a middle-tier component. 然后,中间层组件使用存储过程中的更改来更新原始数据源。The middle-tier component then updates the original data source with the changes through stored procedures. 然后,中间层可以发回包含原始数据的新 DataSet 和数据源中的最新数据(再次运行原始查询),也可以将其从数据源中所做的任何更改发送回。The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (例如,如果数据源自动创建唯一的主键值,则这些值可以传播回客户端应用程序。)在任一情况下,返回的 DataSet 都可以与 Merge 方法一起合并回客户端应用程序的原始 DataSet(For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

调用 Merge 方法时,将比较两个 DataSet 对象的架构,因为架构可能已更改。When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. 例如,在企业对企业方案中,可能已通过自动化过程将新列添加到了 XML 架构。For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. 如果源 DataSet 包含目标中缺少的架构元素(添加 DataColumn 对象),则可以通过将 missingSchemaAction 参数设置为 MissingSchemaAction.Add来将架构元素添加到目标。If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. 在这种情况下,合并的 DataSet 包含添加的架构和数据。In that case, the merged DataSet contains the added schema and data.

合并架构后,数据将合并。After merging schemas, the data is merged.

在将新的源 DataSet 合并到目标时,DataRowState 值为 UnchangedModifiedDeleted 的任何源行都将与具有相同的主键值的目标行匹配。When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. DataRowState 值为 Added 的源行与新源行的主键值相同的新目标行匹配。Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

在合并过程中,将禁用约束。During a merge, constraints are disabled. 如果在合并结束时无法启用任何约束,则会生成 ConstraintException,并在禁用约束时保留合并的数据。If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. 在这种情况下,EnforceConstraints 属性设置为 false,所有无效行都标记为 "错误"。In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. 在尝试将 EnforceConstraints 属性重置为 true之前,必须解决这些错误。The errors must be resolved before attempting to reset the EnforceConstraints property to true.

另请参阅

适用于