DataTable.Merge 方法

定义

将指定的 DataTable 与当前 DataTable 合并。Merge the specified DataTable with the current DataTable.

重载

Merge(DataTable, Boolean, MissingSchemaAction)

将指定的 DataTable 与当前 DataTable 合并,指示是否保留更改以及如何处理当前 DataTable 中缺失的架构。Merge the specified DataTable with the current DataTable, indicating whether to preserve changes and how to handle missing schema in the current DataTable.

Merge(DataTable, Boolean)

将指定的 DataTable 与当前 DataTable 合并,指示是否保留当前 DataTable 中的更改。Merge the specified DataTable with the current DataTable, indicating whether to preserve changes in the current DataTable.

Merge(DataTable)

将指定的 DataTable 与当前 DataTable 合并。Merge the specified DataTable with the current DataTable.

示例

下面的控制台应用程序演示方法的参数的行为 missingSchemaAction MergeThe following console application demonstrates the behavior of the missingSchemaAction parameter of the Merge method. 此示例将创建同一个表的两个版本,并修改第二个版本的架构。This example creates two versions of the same table, modifying the schema for the second version. 然后,该代码会尝试将第二个表合并为第一个表。The code then attempts to merge the second table into the first.

备注

此示例演示如何使用合并的重载版本之一。This example shows how to use one of the overloaded versions of Merge. 有关可能可用的其他示例,请参阅各个重载主题。For other examples that might be available, see the individual overload topics.

private static void DemonstrateMergeTable()
{
    DataTable table1 = new DataTable("Items");

    // Add columns
    DataColumn idColumn = new DataColumn("id", typeof(System.Int32));
    DataColumn itemColumn = new DataColumn("item", typeof(System.Int32));
    table1.Columns.Add(idColumn);
    table1.Columns.Add(itemColumn);

    // Set the primary key column.
    table1.PrimaryKey = new DataColumn[] { idColumn };

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

    // Add ten rows.
    DataRow row;
    for (int i = 0; i <= 9; i++)
    {
        row = table1.NewRow();
        row["id"] = i;
        row["item"] = i;
        table1.Rows.Add(row);
    }

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

    // Create a second DataTable identical to the first.
    DataTable table2 = table1.Clone();

    // Add column to the second column, so that the
    // schemas no longer match.
    table2.Columns.Add("newColumn", typeof(System.String));

    // Add three rows. Note that the id column can't be the
    // same as existing rows in the original table.
    row = table2.NewRow();
    row["id"] = 14;
    row["item"] = 774;
    row["newColumn"] = "new column 1";
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 12;
    row["item"] = 555;
    row["newColumn"] = "new column 2";
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 13;
    row["item"] = 665;
    row["newColumn"] = "new column 3";
    table2.Rows.Add(row);

    // Merge table2 into the table1.
    Console.WriteLine("Merging");
    table1.Merge(table2, false, MissingSchemaAction.Add);
    PrintValues(table1, "Merged With table1, schema added");
}

private static void Row_Changed(object sender,
    DataRowChangeEventArgs e)
{
    Console.WriteLine("Row changed {0}\t{1}", e.Action,
        e.Row.ItemArray[0]);
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn col in table.Columns)
        {
            Console.Write("\t " + row[col].ToString());
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateMergeTable()
  Dim table1 As New DataTable("Items")

  ' Add columns
  Dim idColumn As New DataColumn("id", GetType(System.Int32))
  Dim itemColumn As New DataColumn("item", GetType(System.Int32))
  table1.Columns.Add(idColumn)
  table1.Columns.Add(itemColumn)

  ' Set the primary key column.
  table1.PrimaryKey = New DataColumn() {idColumn}

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

  ' Add some rows.
  Dim row As DataRow
  For i As Integer = 0 To 3
    row = table1.NewRow()
    row("id") = i
    row("item") = i
    table1.Rows.Add(row)
  Next i

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

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

  ' Add column to the second column, so that the 
  ' schemas no longer match.
  table2.Columns.Add("newColumn", GetType(System.String))

  ' Add three rows. Note that the id column can't be the 
  ' same as existing rows in the original table.
  row = table2.NewRow()
  row("id") = 14
  row("item") = 774
  row("newColumn") = "new column 1"
  table2.Rows.Add(row)

  row = table2.NewRow()
  row("id") = 12
  row("item") = 555
  row("newColumn") = "new column 2"
  table2.Rows.Add(row)

  row = table2.NewRow()
  row("id") = 13
  row("item") = 665
  row("newColumn") = "new column 3"
  table2.Rows.Add(row)

  ' Merge table2 into the table1.
  Console.WriteLine("Merging")
  table1.Merge(table2, False, MissingSchemaAction.Add)
  PrintValues(table1, "Merged With table1, Schema added")
End Sub

Private Sub Row_Changed(ByVal sender As Object, _
      ByVal e As DataRowChangeEventArgs)
  Console.WriteLine("Row changed {0}{1}{2}", _
    e.Action, ControlChars.Tab, e.Row.ItemArray(0))
End Sub

Private Sub PrintValues(ByVal table As DataTable, _
      ByVal label As String)
  ' Display the values in the supplied DataTable:
  Console.WriteLine(label)
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(ControlChars.Tab + " " + row(col).ToString())
    Next col
    Console.WriteLine()
  Next row
End Sub

注解

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

Merge 操作仅考虑原始表和要合并的表。The merge operation takes into account only the original table, and the table to be merged. 不会影响或包含子表。Child tables are not affected or included. 如果表具有一个或多个子表(定义为关系的一部分),则每个子表都必须单独合并。If a table has one or more child tables, defined as part of a relationship, each child table must be merged individually.

Merge(DataTable, Boolean, MissingSchemaAction)

将指定的 DataTable 与当前 DataTable 合并,指示是否保留更改以及如何处理当前 DataTable 中缺失的架构。Merge the specified DataTable with the current DataTable, indicating whether to preserve changes and how to handle missing schema in the current DataTable.

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
Public Sub Merge (table As DataTable, preserveChanges As Boolean, missingSchemaAction As MissingSchemaAction)

参数

table
DataTable

要与当前 DataTable 合并的 DataTableThe DataTable to be merged with the current DataTable.

preserveChanges
Boolean

如果保留当前 DataTable 中的更改,则为 true;否则为 falsetrue, to preserve changes in the current DataTable; otherwise false.

missingSchemaAction
MissingSchemaAction

MissingSchemaAction 值之一。One of the MissingSchemaAction values.

示例

下面的控制台应用程序演示方法的参数的行为 missingSchemaAction MergeThe following console application demonstrates the behavior of the missingSchemaAction parameter of the Merge method. 此示例将创建同一个表的两个版本,并修改第二个版本的架构。This example creates two versions of the same table, modifying the schema for the second version. 然后,该代码会尝试将第二个表合并为第一个表。The code then attempts to merge the second table into the first.

private static void DemonstrateMergeTable()
{
    DataTable itemsTable = new DataTable("Items");

    // Add columns
    DataColumn idColumn = new DataColumn("id", typeof(System.Int32));
    DataColumn itemColumn = new DataColumn("item", typeof(System.Int32));
    itemsTable.Columns.Add(idColumn);
    itemsTable.Columns.Add(itemColumn);

    // Set the primary key column.
    itemsTable.PrimaryKey = new DataColumn[] { idColumn };

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

    // Add ten rows.
    DataRow row;
    for (int i = 0; i <= 9; i++)
    {
        row = itemsTable.NewRow();
        row["id"] = i;
        row["item"] = i;
        itemsTable.Rows.Add(row);
    }

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

    // Create a second DataTable identical to the first.
    DataTable itemsClone = itemsTable.Clone();

    // Add column to the second column, so that the
    // schemas no longer match.
    itemsClone.Columns.Add("newColumn", typeof(System.String));

    // Add three rows. Note that the id column can't be the
    // same as existing rows in the original table.
    row = itemsClone.NewRow();
    row["id"] = 14;
    row["item"] = 774;
    row["newColumn"] = "new column 1";
    itemsClone.Rows.Add(row);

    row = itemsClone.NewRow();
    row["id"] = 12;
    row["item"] = 555;
    row["newColumn"] = "new column 2";
    itemsClone.Rows.Add(row);

    row = itemsClone.NewRow();
    row["id"] = 13;
    row["item"] = 665;
    row["newColumn"] = "new column 3";
    itemsClone.Rows.Add(row);

    // Merge itemsClone into the itemsTable.
    Console.WriteLine("Merging");
    itemsTable.Merge(itemsClone, false, MissingSchemaAction.Add);
    PrintValues(itemsTable, "Merged With itemsTable, schema added");
}

private static void Row_Changed(object sender,
    DataRowChangeEventArgs e)
{
    Console.WriteLine("Row changed {0}\t{1}",
        e.Action, e.Row.ItemArray[0]);
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn col in table.Columns)
        {
            Console.Write("\t " + row[col].ToString());
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateMergeTable()
  Dim itemsTable As New DataTable("Items")

  ' Add columns
  Dim idColumn As New DataColumn("id", GetType(System.Int32))
  Dim itemColumn As New DataColumn("item", GetType(System.Int32))
  itemsTable.Columns.Add(idColumn)
  itemsTable.Columns.Add(itemColumn)

  ' Set the primary key column.
  itemsTable.PrimaryKey = New DataColumn() {idColumn}

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

  ' Add some rows.
  Dim row As DataRow
  For i As Integer = 0 To 3
    row = itemsTable.NewRow()
    row("id") = i
    row("item") = i
    itemsTable.Rows.Add(row)
  Next i

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

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

  ' Add column to the second column, so that the 
  ' schemas no longer match.
  itemsClone.Columns.Add("newColumn", GetType(System.String))

  ' Add three rows. Note that the id column can't be the 
  ' same as existing rows in the original table.
  row = itemsClone.NewRow()
  row("id") = 14
  row("item") = 774
  row("newColumn") = "new column 1"
  itemsClone.Rows.Add(row)

  row = itemsClone.NewRow()
  row("id") = 12
  row("item") = 555
  row("newColumn") = "new column 2"
  itemsClone.Rows.Add(row)

  row = itemsClone.NewRow()
  row("id") = 13
  row("item") = 665
  row("newColumn") = "new column 3"
  itemsClone.Rows.Add(row)

  ' Merge itemsClone into the itemsTable.
  Console.WriteLine("Merging")
  itemsTable.Merge(itemsClone, False, MissingSchemaAction.Add)
  PrintValues(itemsTable, "Merged With itemsTable, Schema added")
End Sub

Private Sub Row_Changed(ByVal sender As Object, _
  ByVal e As DataRowChangeEventArgs)
  Console.WriteLine("Row changed {0}{1}{2}", _
    e.Action, ControlChars.Tab, e.Row.ItemArray(0))
End Sub

Private Sub PrintValues(ByVal table As DataTable, ByVal label As String)
  ' Display the values in the supplied DataTable:
  Console.WriteLine(label)
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(ControlChars.Tab + " " + row(col).ToString())
    Next col
    Console.WriteLine()
  Next row
End Sub

注解

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

Merge 操作仅考虑原始表和要合并的表。The merge operation takes into account only the original table, and the table to be merged. 不会影响或包含子表。Child tables are not affected or included. 如果表具有一个或多个子表(定义为关系的一部分),则每个子表都必须单独合并。If a table has one or more child tables, defined as part of a relationship, each child table must be merged individually.

Merge方法通常在一系列过程的末尾调用,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataTableThe 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 DataTable.

执行合并时,将在合并操作期间保留对现有数据所做的更改,除非开发人员为参数指定 false preserveChangesWhen performing a merge, changes made to the existing data before the merge are preserved during the merge operation unless the developer specifies false for the preserveChanges parameter. 如果将 preserveChanges 参数设置为 true ,则传入值不会覆盖现有行的当前行版本中的现有值。If the preserveChanges parameter is set to true, incoming values do not overwrite existing values in the Current row version of the existing row. 如果将 preserveChanges 参数设置为 false ,则传入值将覆盖现有行的当前行版本中的现有值。If the preserveChanges parameter is set to false, incoming values do overwrite the existing values in the Current row version of the existing row. 有关行版本的详细信息,请参阅 行状态和行版本For more information about row versions, see Row States and Row Versions.

在客户端应用程序中,通常会有一个按钮,用户可以单击该按钮来收集更改的数据并对其进行验证,然后再将其发送回中间层组件。In a client application, it is usual 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. 该方法将返回第二个 DataTable 优化用于验证和合并的。That method returns a second DataTable optimized for validating and merging. 此第二个 DataTable 对象仅包含已 DataTable 更改的和 DataRow 对象,从而导致了原始的子集 DataTableThis second DataTable object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataTable. 此子集通常较小,因此此子集更有效地传递回中间层组件。This subset is generally smaller, and thus this subset is 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. 然后,中间层可以 DataTable 通过再次运行原始查询来发送回包含数据源中的原始数据和最新数据 (的新数据) ,也可以从数据源向后发送回已对其进行的任何更改的子集。The middle tier can then send back either a new DataTable 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. (例如,如果数据源自动创建唯一的主键值,则这些值可以传播回客户端应用程序。 ) 在任何一种情况下,返回的都 DataTable 可以 DataTable 通过 Merge 方法合并回客户端应用程序的原始中。(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 DataTable can be merged back into the client application's original DataTable with the Merge method.

Merge调用方法时,将比较两个对象的架构 DataTable ,因为架构可能已更改。When the Merge method is called, the schemas of the two DataTable 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. 如果源 DataTable 包含架构元素 (添加了 DataColumn 目标中缺少的对象) ,则可以通过将参数设置为来将架构元素添加到目标中 missingSchemaAction MissingSchemaAction.AddIf the source DataTable 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. 在这种情况下,合并的 DataTable 包含已添加的架构和数据。In that case, the merged DataTable contains the added schema and data.

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

在将新源合并 DataTable 到目标时,值为、或的任何源行都将与 DataRowState Unchanged Modified Deleted 具有相同的主键值的目标行匹配。When merging a new source DataTable 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.

适用于

Merge(DataTable, Boolean)

将指定的 DataTable 与当前 DataTable 合并,指示是否保留当前 DataTable 中的更改。Merge the specified DataTable with the current DataTable, indicating whether to preserve changes in the current DataTable.

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

参数

table
DataTable

要与当前 DataTable 合并的 DataTableThe DataTable to be merged with the current DataTable.

preserveChanges
Boolean

如果保留当前 DataTable 中的更改,则为 true;否则为 falsetrue, to preserve changes in the current DataTable; otherwise false.

示例

下面的控制台应用程序创建一个 DataTable 包含行,修改这些行中的某些数据,并尝试从不同的合并数据 DataTableThe following console application creates a DataTable containing rows, modifies some of the data in those rows, and attempts to merge data from a different DataTable. 该示例演示参数的不同行为 preserveChangesThe example demonstrates the different behaviors for the preserveChanges parameter.


private static void DemonstrateMergeTable()
{
    // Demonstrate merging, within and without
    // preserving changes.

    // In this example, take these actions:
    // 1. Create a DataTable (table1) and fill the table with data.
    // 2. Create a copy of table1, and modify its data (modifiedTable).
    // 3. Modify data in table1.
    // 4. Make a copy of table1 (table1Copy).
    // 5. Merge the data from modifiedTable into table1 and table1Copy,
    //    showing the difference between setting the preserveChanges
    //    parameter to true and false.

    // Create a new DataTable.
    DataTable table1 = new DataTable("Items");

    // Add two columns to the table:
    DataColumn column = new DataColumn("id", typeof(System.Int32));
    column.AutoIncrement = true;
    table1.Columns.Add(column);

    column = new DataColumn("item", typeof(System.String));
    table1.Columns.Add(column);

    // Set primary key column.
    table1.PrimaryKey = new DataColumn[] { table1.Columns[0] };

    // Add some rows.
    DataRow row;
    for (int i = 0; i <= 3; i++)
    {
        row = table1.NewRow();
        row["item"] = "Item " + i;
        table1.Rows.Add(row);
    }

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

    // Using the same schema as the original table,
    // modify the data for later merge.
    DataTable modifiedTable = table1.Copy();
    foreach (DataRow rowModified in modifiedTable.Rows)
    {
        rowModified["item"] = rowModified["item"].ToString()
            + " modified";
    }
    modifiedTable.AcceptChanges();

    // Change row values, and add a new row:
    table1.Rows[0]["item"] = "new Item 0";
    table1.Rows[1]["item"] = "new Item 1";

    row = table1.NewRow();
    row["id"] = 4;
    row["item"] = "Item 4";
    table1.Rows.Add(row);

    // Get a copy of the modified data:
    DataTable table1Copy = table1.Copy();
    PrintValues(table1, "Modified and new Values");
    PrintValues(modifiedTable, "Data to be merged into table1");

    // Merge new data into the modified data.
    table1.Merge(modifiedTable, true);
    PrintValues(table1, "Merged data (preserve changes)");

    table1Copy.Merge(modifiedTable, false);
    PrintValues(table1Copy, "Merged data (don't preserve changes)");
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            Console.Write("\t{0}", row[column, DataRowVersion.Current]);
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateMergeTable()
  ' Demonstrate merging, within and without
  ' preserving changes.

  ' In this example, take these actions:
  ' 1. Create a DataTable (table1) and fill the table with data.
  ' 2. Create a copy of table1, and modify its data (modifiedTable).
  ' 3. Modify data in table1.
  ' 4. Make a copy of table1 (table1Copy).
  ' 5. Merge the data from modifiedTable into table1 and table1Copy, 
  '    showing the difference between setting the preserveChanges 
  '    parameter to true and false.

  ' Create a new DataTable.
  Dim table1 As New DataTable("Items")

  ' Add two columns to the table:
  Dim column As New DataColumn("id", GetType(System.Int32))
  column.AutoIncrement = True
  table1.Columns.Add(column)

  column = New DataColumn("item", GetType(System.String))
  table1.Columns.Add(column)

  ' Set primary key column.
  table1.PrimaryKey = New DataColumn() {table1.Columns(0)}

  ' Add some rows.
  Dim row As DataRow
  For i As Integer = 0 To 3
    row = table1.NewRow()
    row("item") = "Item " & i
    table1.Rows.Add(row)
  Next i

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

  ' Using the same schema as the original table, 
  ' modify the data for later merge.
  Dim modifiedTable As DataTable = table1.Copy()
  For Each row In modifiedTable.Rows
    row("item") = row("item").ToString() & " modified"
  Next
  modifiedTable.AcceptChanges()

  ' Change row values, and add a new row:
  table1.Rows(0)("item") = "New Item 0"
  table1.Rows(1)("item") = "New Item 1"

  row = table1.NewRow()
  row("id") = 4
  row("item") = "Item 4"
  table1.Rows.Add(row)

  ' Get a copy of the modified data:
  Dim table1Copy As DataTable = table1.Copy()
  PrintValues(table1, "Modified and New Values")
  PrintValues(modifiedTable, "Data to be merged into table1")


  ' Merge new data into the modified data.
  table1.Merge(modifiedTable, True)
  PrintValues(table1, "Merged data (preserve changes)")

  table1Copy.Merge(modifiedTable, False)
  PrintValues(table1Copy, "Merged data (don't preserve changes)")

End Sub

Private Sub PrintValues(ByVal table As DataTable, _
  ByVal label As String)

  ' Display the values in the supplied DataTable:
  Console.WriteLine(label)
  For Each row As DataRow In table.Rows
    For Each column As DataColumn In table.Columns
      Console.Write("{0}{1}", ControlChars.Tab, row(column, _
          DataRowVersion.Current))
    Next column
    Console.WriteLine()
  Next row
End Sub

注解

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

Merge 操作仅考虑原始表和要合并的表。The merge operation takes into account only the original table, and the table to be merged. 不会影响或包含子表。Child tables are not affected or included. 如果表具有一个或多个子表(定义为关系的一部分),则每个子表都必须单独合并。If a table has one or more child tables, defined as part of a relationship, each child table must be merged individually.

Merge方法通常在一系列过程的末尾调用,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataTableThe 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 DataTable.

执行合并时,将在合并操作期间保留对现有数据所做的更改,除非开发人员为参数指定 false preserveChangesWhen performing a merge, changes made to the existing data before the merge are preserved during the merge operation unless the developer specifies false for the preserveChanges parameter. 如果将 preserveChanges 参数设置为 true ,则传入值不会覆盖现有行的当前行版本中的现有值。If the preserveChanges parameter is set to true, incoming values do not overwrite existing values in the Current row version of the existing row. 如果将 preserveChanges 参数设置为 false ,则传入值将覆盖现有行的当前行版本中的现有值。If the preserveChanges parameter is set to false, incoming values do overwrite the existing values in the Current row version of the existing row. 有关行版本的详细信息,请参阅 行状态和行版本For more information about row versions, see Row States and Row Versions.

在客户端应用程序中,通常会有一个按钮,用户可以单击该按钮来收集更改的数据并对其进行验证,然后再将其发送回中间层组件。In a client application, it is usual 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. 该方法将返回第二个 DataTable 优化用于验证和合并的。That method returns a second DataTable optimized for validating and merging. 此第二个 DataTable 对象仅包含已 DataTable 更改的和 DataRow 对象,从而导致了原始的子集 DataTableThis second DataTable object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataTable. 此子集通常较小,因此此子集更有效地传递回中间层组件。This subset is generally smaller, and thus this subset is 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. 然后,中间层可以 DataTable 通过再次运行原始查询来发送回包含数据源中的原始数据和最新数据 (的新数据) ,也可以从数据源向后发送回已对其进行的任何更改的子集。The middle tier can then send back either a new DataTable 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. (例如,如果数据源自动创建唯一的主键值,则这些值可以传播回客户端应用程序。 ) 在任何一种情况下,返回的都 DataTable 可以 DataTable 通过 Merge 方法合并回客户端应用程序的原始中。(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 DataTable can be merged back into the client application's original DataTable with the Merge method.

在将新源合并 DataTable 到目标时,值为、或的任何源行都将与 DataRowState Unchanged Modified Deleted 具有相同的主键值的目标行匹配。When merging a new source DataTable 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.

适用于

Merge(DataTable)

将指定的 DataTable 与当前 DataTable 合并。Merge the specified DataTable with the current DataTable.

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

要与当前 DataTable 合并的 DataTableThe DataTable to be merged with the current DataTable.

示例

下面的控制台应用程序创建一个简单的 DataTable ,并将数据添加到表中。The following console application creates a simple DataTable and adds data to the table. 然后,该示例将创建表的副本,并向副本添加行。The example then creates a copy of the table, adding rows to the copy. 最后,该示例调用 Merge 方法,将第二个表中的数据与第一个表中的数据合并。Finally, the example calls the Merge method to merge the data in the second table with the data in the first table.

private static void DemonstrateMergeTable()
{
    DataTable table1 = new DataTable("Items");

    // Add columns
    DataColumn column1 = new DataColumn("id", typeof(System.Int32));
    DataColumn column2 = new DataColumn("item", typeof(System.Int32));
    table1.Columns.Add(column1);
    table1.Columns.Add(column2);

    // Set the primary key column.
    table1.PrimaryKey = new DataColumn[] { column1 };

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

    // Add some rows.
    DataRow row;
    for (int i = 0; i <= 3; i++)
    {
        row = table1.NewRow();
        row["id"] = i;
        row["item"] = i;
        table1.Rows.Add(row);
    }

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

    // Create a second DataTable identical to the first.
    DataTable table2 = table1.Clone();

    // Add three rows. Note that the id column can't be the
    // same as existing rows in the original table.
    row = table2.NewRow();
    row["id"] = 14;
    row["item"] = 774;
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 12;
    row["item"] = 555;
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 13;
    row["item"] = 665;
    table2.Rows.Add(row);

    // Merge table2 into the table1.
    Console.WriteLine("Merging");
    table1.Merge(table2);
    PrintValues(table1, "Merged With table1");
}

private static void Row_Changed(object sender,
    DataRowChangeEventArgs e)
{
    Console.WriteLine("Row changed {0}\t{1}",
        e.Action, e.Row.ItemArray[0]);
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn col in table.Columns)
        {
            Console.Write("\t " + row[col].ToString());
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateMergeTable()
  Dim table1 As New DataTable("Items")

  ' Add columns
  Dim column1 As New DataColumn("id", GetType(System.Int32))
  Dim column2 As New DataColumn("item", GetType(System.Int32))
  table1.Columns.Add(column1)
  table1.Columns.Add(column2)

  ' Set the primary key column.
  table1.PrimaryKey = New DataColumn() {column1}

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

  ' Add some rows.
  Dim row As DataRow
  For i As Integer = 0 To 3
    row = table1.NewRow()
    row("id") = i
    row("item") = i
    table1.Rows.Add(row)
  Next i

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

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

  ' Add three rows. Note that the id column can't be the 
  ' same as existing rows in the original table.
  row = table2.NewRow()
  row("id") = 14
  row("item") = 774
  table2.Rows.Add(row)

  row = table2.NewRow()
  row("id") = 12
  row("item") = 555
  table2.Rows.Add(row)

  row = table2.NewRow()
  row("id") = 13
  row("item") = 665
  table2.Rows.Add(row)

  ' Merge table2 into the table1.
  Console.WriteLine("Merging")
  table1.Merge(table2)
  PrintValues(table1, "Merged With table1")

End Sub

Private Sub Row_Changed(ByVal sender As Object, _
  ByVal e As DataRowChangeEventArgs)
  Console.WriteLine("Row changed {0}{1}{2}", _
    e.Action, ControlChars.Tab, e.Row.ItemArray(0))
End Sub

Private Sub PrintValues(ByVal table As DataTable, _
  ByVal label As String)
  ' Display the values in the supplied DataTable:
  Console.WriteLine(label)
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(ControlChars.Tab + " " + row(col).ToString())
    Next col
    Console.WriteLine()
  Next row
End Sub

注解

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

Merge 操作仅考虑原始表和要合并的表。The merge operation takes into account only the original table, and the table to be merged. 不会影响或包含子表。Child tables are not affected or included. 如果表具有一个或多个子表(定义为关系的一部分),则每个子表都必须单独合并。If a table has one or more child tables, defined as part of a relationship, each child table must be merged individually.

Merge方法通常在一系列过程的末尾调用,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataTableThe 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 DataTable.

执行合并时,默认情况下,合并操作期间将保留对现有数据所做的更改。When performing a merge, changes made to the existing data before the merge are preserved by default during the merge operation. 开发人员可以通过调用此方法的另一个重载,并为参数指定 false 值来修改此行为 preserveChangesDevelopers can modify this behavior by calling one of the other two overloads for this method, and specifying a false value for the preserveChanges parameter.

在客户端应用程序中,通常会有一个按钮,用户可以单击该按钮来收集更改的数据并对其进行验证,然后再将其发送回中间层组件。In a client application, it is usual 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. 该方法将返回第二个 DataTable 优化用于验证和合并的。That method returns a second DataTable optimized for validating and merging. 此第二个 DataTable 对象仅包含已 DataRow 更改的对象,从而生成原始对象的子集 DataTableThis second DataTable object contains only the DataRow objects that were changed, resulting in a subset of the original DataTable. 此子集通常较小,因此更有效地传递回中间层组件。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. 然后,中间层可以 DataTable 通过再次运行原始查询来发送回包含数据源中的原始数据和最新数据 (的新数据) ,也可以从数据源向后发送回已对其进行的任何更改的子集。The middle tier can then send back either a new DataTable 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. (例如,如果数据源自动创建唯一的主键值,则这些值可以传播回客户端应用程序。 ) 在任何一种情况下,返回的都 DataTable 可以 DataTable 通过 Merge 方法合并回客户端应用程序的原始中。(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 DataTable can be merged back into the client application's original DataTable with the Merge method.

在将新源合并 DataTable 到目标时,任何值为、或的源行都将与 DataRowState Unchanged Modified Deleted 具有相同的主键值的目标行匹配。When merging a new source DataTable into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted, is 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.

适用于