2.11. Building a DataSet Programmatically

Problem

You want to build a DataSet programmatically—including adding tables, columns, primary keys, and relations—from a schema that you have designed.

Solution

The following example shows how to build a complex DataSet programmatically, including how to build and add tables, columns, primary key constraints, relations, and column mappings. Use this as a template for building your own DataSet.

The solution creates a DataSet. A DataTable object containing sales order header data is created. Columns are added, including the autoincrement primary key, to the table. The table is added to the DataSet. The process is repeated for a DataTable containing sales order detail data. A DataRelation is created relating the two tables. Finally, the tables are filled with data from the Sales.SalesOrderHeader and Sales.SalesOrderDetail data from the AdventureWorks database using a DataAdapter. Data from the DataSet is output to the console.

The C# code in Program.cs in the project BuildDataSetProgrammatically is shown in Example 2-11.

Example 2-11. File: Program.cs for BuildDataSetProgramatically solution

using System; using System.Data; using System.Data.SqlClient; namespace BuildDataSetProgrammatically { class Program { static void Main(string[] args) { DataSet ds = new DataSet("SalesOrders"); // Build the SaleOrderHeader (parent) table DataTable dtHeader = new DataTable("SalesOrderHeader"); // Get the collection of columns for the parent table DataColumnCollection ...

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.