Home > Articles > Programming > Windows Programming

The Strongly Typed DataSet

The strongly typed DataSet fills a special role in the world of ADO.NET. It makes the DataSet look more like an object from the data domain it models, by using typed properties instead of polymorphic, generic collections. It does this magic through implementation inheritance of the DataSet, DataTable, and DataRow objects along with augmentation code to wire the structure together when the root DataSet-based class is instantiated. The end result is easier navigation and better data retrieval and storage, without pesky runtime type or column errors.

The first step in creating a strongly typed DataSet is adding an XML schema file that will represent its structure to a project. The best way to do this is use the Data Set item in the Add New Item menu option of the IDE as it creates the XML schema file and adds DataSet-specific namespaces and attributes to the schema document. In Figure 6, notice that the file type extension is xsd for the CustOrders DataSet being created.

Figure 6Figure 6 Using Add New Item to add a typed DataSet.

The next step in the process is to add the data structures. We continue with our incessant demo loop of the Customers and Orders tables from Northwind to do them in a strongly typed manner. The easiest way to add tables is to select them in the Server Explorer Database node and drag them onto the design surface of the typed DataSet, as shown in Figure 7. The XML schema document representing the DataSet gets the metadata from the database tables to represent them faithfully after the UI manipulation. This brings us to the picture depicted in Figure 8. The IDE is not equipped to link the two tables; we're responsible for creating the relationship between them. Fortunately, we have the XML toolbox at our disposal. Select the Relation control and drag it onto the Customers table sitting in the designer surface. This will pop up a dialog like that in Figure 9, which has all the information necessary to link the two tables.

Figure 7Figure 7 Dragging Customers and Orders onto typed DataSet.

Figure 8Figure 8 XML toolbox options.

Figure 9Figure 9 Relationship-building dialog.

Listing 5 shows the resulting XML schema document, generated and viewable from the XML tab of the XSD document. Microsoft extensions to the XML schema document are scoped using the msdata namespace to help identify the schema as belonging to a typed DataSet, as well as helping with the auto-increment OrderID field and the CustomerID primary and foreign keys. These attributes don't get in the way of interoperability with other platforms or environments; XML parsers and validators ignore the attributes that are not scoped by the XML Schema namespace.

Listing 5—Final Typed DataSet Xml Schema

<?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema id="CustOrders" 
targetNamespace="http://tempuri.org/CustOrders.xsd" 
elementFormDefault="qualified"
attributeFormDefault="qualified" 
xmlns="http://tempuri.org/CustOrders.xsd" 
xmlns:mstns="http://tempuri.org/CustOrders.xsd" 
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="CustOrders" msdata:IsDataSet="true">
 <xs:complexType>
  <xs:choice maxOccurs="unbounded">
  <xs:element name="Customers">
   <xs:complexType>
    <xs:sequence>
      <xs:element name="CustomerID" type="xs:string" />
      <xs:element name="CompanyName" type="xs:string" />
      <xs:element name="ContactName" type="xs:string"
       minOccurs="0" />
   <xs:element name="ContactTitle" type="xs:string"
       minOccurs="0" />
      <xs:element name="Address" type="xs:string"
       minOccurs="0" />
      <xs:element name="City" type="xs:string"
       minOccurs="0" />
      <xs:element name="Region" type="xs:string"
       minOccurs="0" />
      <xs:element name="PostalCode" type="xs:string"
       minOccurs="0" />
      <xs:element name="Country" type="xs:string"
       minOccurs="0" />
      <xs:element name="Phone" type="xs:string"
       minOccurs="0" />
      <xs:element name="Fax" type="xs:string"
       minOccurs="0" />
     </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="Orders">
   <xs:complexType>
    <xs:sequence>
   <xs:element name="OrderID"
       msdata:ReadOnly="true"
       msdata:AutoIncrement="true"
       type="xs:int" />
      <xs:element name="CustomerID" type="xs:string"
       minOccurs="0" />
      <xs:element name="EmployeeID" type="xs:int"
       minOccurs="0" />
      <xs:element name="OrderDate" type="xs:dateTime"
       minOccurs="0" />
      <xs:element name="RequiredDate" type="xs:dateTime"
       minOccurs="0" />
      <xs:element name="ShippedDate" type="xs:dateTime"
       minOccurs="0" />
      <xs:element name="ShipVia" type="xs:int"
       minOccurs="0" />
      <xs:element name="Freight" type="xs:decimal"
       minOccurs="0" />
      <xs:element name="ShipName" type="xs:string"
       minOccurs="0" />
      <xs:element name="ShipAddress" type="xs:string"
       minOccurs="0" />
      <xs:element name="ShipCity" type="xs:string"
       minOccurs="0" />
      <xs:element name="ShipRegion" type="xs:string"
       minOccurs="0" />
      <xs:element name="ShipPostalCode" type="xs:string"
       minOccurs="0" />
      <xs:element name="ShipCountry" type="xs:string"
       minOccurs="0" />
     </xs:sequence>
    </xs:complexType>
   </xs:element>
  </xs:choice>
 </xs:complexType>
 <xs:unique name="CustOrdersKey1"
   msdata:PrimaryKey="true">
  <xs:selector xpath=".//mstns:Customers" />
  <xs:field xpath="mstns:CustomerID" />
 </xs:unique>
 <xs:unique name="CustOrdersKey2" msdata:PrimaryKey="true">
  <xs:selector xpath=".//mstns:Orders" />
  <xs:field xpath="mstns:OrderID" />
 </xs:unique>
 <xs:keyref name="CustOrders" refer="CustOrdersKey1">
  <xs:selector xpath=".//mstns:Orders" />
  <xs:field xpath="mstns:CustomerID" />
 </xs:keyref>
</xs:element>
</xs:schema>

Once the schema document is added to the solution, the IDE defaults to automatically generating a typed DataSet class during project builds. The menu option for the XML schema document in Figure 10 and the Solution Explorer picture with the generated CustOrders.cs file in Figure 11 confirm this. The generated class file is visible in the Solution Explorer if you select the Show All Files icon, which is highlighted in blue in Figure 11.

Figure 10Figure 10 Generate DataSet.

Figure 11Figure 11 Strongly typed DataSet in Solution Explorer.

The strongly typed DataSet works in a similar manner to the regular DataSet. In the TypedDataSet form class in Listing 6, we use the predefined helper classes to load the DataSet using a DataAdapter in a manner identical to previous demos in this article. The main difference is the lack of linking; a typed DataSet comes pre-built with relationships. The code also demonstrates how to add a row, do navigation between tables, and pull property values from the rows manually (as contrasted with data binding). This demonstrates the ease of use and built-in error prevention. A screenshot of the demo form is depicted in Figure 12.

Listing 6—TypedDataSet Form to Manipulate a Strongly Typed DataSet

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;


namespace DisconnectedOpsIIDemo
{
  /// <summary>
  /// Summary description for TypedDataSet.
  /// </summary>
  public class TypedDataSet : System.Windows.Forms.Form
  {
   [STAThread]
   static void Main(string[] args)
   {
     Application.Run(new TypedDataSet());
   }


   private CustOrders TCustDS;
   private System.Windows.Forms.ListBox listBox1;
   private System.Windows.Forms.DataGrid dataGrid1;

   /// <summary>
   /// Required designer variable.
   /// </summary>
   private System.ComponentModel.Container components = null;

   public TypedDataSet()
   {
     //
     // Required for Windows Form Designer support
     //
     InitializeComponent();

     //
     // TODO: Add any constructor code after
     // InitializeComponent call
     //
   }

   /// <summary>
   /// Clean up any resources being used.
   /// </summary>
   protected override void Dispose( bool disposing )
   {
     if( disposing )
     {
      if(components != null)
      {
        components.Dispose();
      }
     }
     base.Dispose( disposing );
   }

   #region Windows Form Designer generated code
   /// <summary>
   /// Required method for Designer support - do not modify
   /// the contents of this method with the code editor.
   /// </summary>
   private void InitializeComponent()
   {
     this.listBox1 =
      new System.Windows.Forms.ListBox();
     this.dataGrid1 =
      new System.Windows.Forms.DataGrid();
     ((System.ComponentModel.ISupportInitialize)
      (this.dataGrid1)).BeginInit();
     this.SuspendLayout();
     //
     // listBox1
     //
     this.listBox1.Location =
      new System.Drawing.Point(8, 176);
     this.listBox1.Name = "listBox1";
     this.listBox1.Size =
      new System.Drawing.Size(496, 160);
     this.listBox1.TabIndex = 0;
     //
     // dataGrid1
     //
     this.dataGrid1.DataMember = "";
     this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
     this.dataGrid1.Location =
      new System.Drawing.Point(8, 8);
     this.dataGrid1.Name = "dataGrid1";
     this.dataGrid1.Size =
      new System.Drawing.Size(496, 160);
     this.dataGrid1.TabIndex = 1;
     //
     // TypedDataSet
     //
     this.AutoScaleBaseSize =
      new System.Drawing.Size(5, 13);
     this.ClientSize =
      new System.Drawing.Size(512, 349);
     this.Controls.AddRange(
      new System.Windows.Forms.Control[] {
         this.dataGrid1,
         this.listBox1});
     this.Name = "TypedDataSet";
     this.Text = "TypedDataSet";
     this.Load +=
      new
      System.EventHandler(this.TypedDataSet_Load);
     ((System.ComponentModel.ISupportInitialize)
      (this.dataGrid1)).EndInit();
     this.ResumeLayout(false);

   }
   #endregion



   private void TypedDataSet_Load(object sender,
     System.EventArgs e)
   {
     // load the typed DataSet and bind it to
     // a DataGrid control
     TCustDS = new CustOrders();
     DataAdapterUtility.LoadCustomers(TCustDS);
     DataAdapterUtility.LoadOrders(TCustDS);
     dataGrid1.DataSource = TCustDS.Customers;


     // add a customer
     CustOrders.CustomersRow newCustRow =
      TCustDS.Customers.AddCustomersRow(
      "ACME", "Acme Corp", "Dale Michalk",
      "No Title", "100 Main Street",
      "Utopia", "NY", "12345", "US",
      "555 555 5555","666 666 6666");

     // add an order
     TCustDS.Orders.AddOrdersRow(newCustRow,
      1, DateTime.Now, DateTime.Now,
      DateTime.Now, 1, 100.00M,
      "Airborne", "100 Main Street",
      "Utopia", "NY", "12345", "US");

     // navigate through the typed DataSet
     foreach (CustOrders.CustomersRow custRow
          in TCustDS.Customers.Rows)
     {
      listBox1.Items.Add(
        "Customer: " + custRow.ContactName);

      CustOrders.OrdersRow[] orderRows =
        custRow.GetOrdersRows();

      int orderCount = orderRows.Length;
      for (int index = 0; index < orderCount; index++)
      {
        listBox1.Items.Add(
         "\tOrder:" + orderRows[index].OrderID +
         " Date:" + orderRows[index].OrderDate);
      }
     }


   }
  }
}

Figure 12Figure 12 TypedDataSet form display.

You can see the man behind the curtain by cracking open the auto-generated CustOrders.cs class file. The InitClass of the CustOrders in Listing 7 is the most interesting because it orchestrates most of the initialization by creating the custom CustomersDataTable and OrdersDataTable members, as well as pre-wiring the constraints and relationships between them. Each table does its own work as well. Listing 8 shows how the CustomersDataTable InitClass method adds its column definitions. The rest of the details of the CustOrder class are left to the reader to spelunk and explore.

Listing 7—Initializing the Strongly Typed DataSet

private void InitClass() {
  this.DataSetName = "CustOrders";
  this.Prefix = "";
  this.Namespace =
  "http://tempuri.org/CustOrders.xsd";
  this.Locale =
  new System.Globalization.CultureInfo("en-US");
  this.CaseSensitive = false;
  this.EnforceConstraints = true;
  this.tableCustomers =
  new CustomersDataTable();
  this.Tables.Add(this.tableCustomers);
  this.tableOrders = new OrdersDataTable();
  this.Tables.Add(this.tableOrders);
  ForeignKeyConstraint fkc;
  fkc =
  new ForeignKeyConstraint("CustOrders",
  new DataColumn[] {
        this.tableCustomers.CustomerIDColumn},
  new DataColumn[] {
        this.tableOrders.CustomerIDColumn});
  this.tableOrders.Constraints.Add(fkc);
  fkc.AcceptRejectRule = AcceptRejectRule.None;
  fkc.DeleteRule = Rule.Cascade;
  fkc.UpdateRule = Rule.Cascade;
  this.relationCustOrders =
  new DataRelation("CustOrders", new DataColumn[] {
        this.tableCustomers.CustomerIDColumn},
  new DataColumn[] {
        this.tableOrders.CustomerIDColumn}, false);
  this.Relations.Add(this.relationCustOrders);
}

Listing 8—Initializing the Strongly Typed Customers Table

private void InitClass() {
  this.columnCustomerID =
  new DataColumn("CustomerID",
  typeof(string), null, System.Data.MappingType.Element);
  this.Columns.Add(this.columnCustomerID);
  this.columnCompanyName =
  new DataColumn("CompanyName", typeof(string), null,
  System.Data.MappingType.Element);
  this.Columns.Add(this.columnCompanyName);
  this.columnContactName =
  new DataColumn("ContactName", typeof(string), null,
  System.Data.MappingType.Element);
  this.Columns.Add(this.columnContactName);
  this.columnContactTitle =
  new DataColumn("ContactTitle", typeof(string), null,
  System.Data.MappingType.Element);
  this.Columns.Add(this.columnContactTitle);
  this.columnAddress =
  new DataColumn("Address", typeof(string), null,
  System.Data.MappingType.Element);
  this.Columns.Add(this.columnAddress);
  this.columnCity =
  new DataColumn("City", typeof(string), null,
  System.Data.MappingType.Element);
  this.Columns.Add(this.columnCity);
  this.columnRegion =
  new DataColumn("Region", typeof(string), null,
  System.Data.MappingType.Element);
  this.Columns.Add(this.columnRegion);
  this.columnPostalCode =
  new DataColumn("PostalCode", typeof(string), null,
  System.Data.MappingType.Element);
  this.Columns.Add(this.columnPostalCode);
  this.columnCountry =
  new DataColumn("Country",
  typeof(string), null, System.Data.MappingType.Element);
  this.Columns.Add(this.columnCountry);
  this.columnPhone =
  new DataColumn("Phone", typeof(string), null,
  System.Data.MappingType.Element);
  this.Columns.Add(this.columnPhone);
  this.columnFax =
  new DataColumn("Fax", typeof(string), null,
  System.Data.MappingType.Element);
  this.Columns.Add(this.columnFax);
  this.Constraints.Add(
  new UniqueConstraint("CustOrdersKey1", new DataColumn[] {
          this.columnCustomerID}, true));
  this.columnCustomerID.AllowDBNull = false;
  this.columnCustomerID.Unique = true;
  this.columnCompanyName.AllowDBNull = false;
}

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020