6.9. Merging Data in Two DataSet Objects

Problem

You have two DataSet objects with the same schema, each containing different data. You need to combine data from these two DataSet objects, merging the changes and without creating duplicate rows.

Solution

Use the DataSet.Merge() method with the appropriate MissingSchemaAction enumeration values.

The solution creates two DataSet objects each with a single DataTable containing a different subset of data from the Person.Contact table in AdventureWorks. The content of each is output to the console. Both DataSet objects are merged into a third DataSet using the Merge() method. The content of the merged DataSet is output to the console.

The C# code in Program.cs in the project MergeDataSets is shown in Example 6-9.

Example 6-9. File: Program.cs for MergeDataSets solution

using System; using System.Data; using System.Data.SqlClient; namespace MergeDataSets { class Program { static void Main(string[] args) { string sqlConnectString = "Data Source=(local);" + "Integrated security=SSPI;Initial Catalog=AdventureWorks;"; string sqlSelect1 = "SELECT ContactID, FirstName, LastName " + "FROM Person.Contact WHERE ContactID BETWEEN 1 AND 4"; string sqlSelect2 = "SELECT ContactID, FirstName, LastName " + "FROM Person.Contact WHERE ContactID BETWEEN 5 AND 8"; // Fill the first DataSet and output DataSet ds1 = new DataSet( ); SqlDataAdapter da1 = new SqlDataAdapter(sqlSelect1, sqlConnectString); da1.TableMappings.Add("Table", "Contact"); da1.FillSchema(ds1, ...

Get ADO.NET 3.5 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.