Home > Articles

This chapter is from the book

Working with Typed Datasets

As mentioned earlier in the chapter, typed datasets are not a separate set of ADO.NET classes. Instead, they are derived directly from the standard ADO.NET classes and define extra members that are specific to your database schema. To understand the main benefit of typed datasets, think of how data has been accessed throughout this chapter using the generic DataRow::Item property, where column name or index value is specified. Because the Item property has no intimate knowledge of the underlying data schema, any mistakes made when using it—such as such as misspelling the column name or using an incompatible data type—aren't realized until runtime. Conversely, typed datasets are generated directly from the database schema and thus produce members that allow for compile-time checking of these common mistakes.

In this section, I'll first illustrate—step-by-step—how to generate a typed dataset for the SQL Server sample Northwind database's Employees table. After that, I'll introduce an MFC SDI application that uses a typed dataset to list all records from the Employees table. Finally, I'll wrap up the section—and chapter—with a listing of the pros and cons of using untyped vs. typed datasets.

Generating a Typed Dataset

Now let's see how to use Visual Studio .NET to generate a typed dataset. As stated at the outset of this chapter, the demo will be using the SQL Server sample Northwind database.

  1. Either create a new project with support for Managed Extensions, or open an existing Managed Extensions project.

  2. Select the Add New Item option from the Project menu (or from the project's context menu in the Solution Explorer).

  3. When the Add New Item dialog appears (Figure 6-5), click the Data folder (category) on the left and then the DataSet icon (template) on the right.

    06fig05.jpgFigure 6-5. Visual Studio .NET provides a template for generating typed datasets.

  4. Enter a name for the header file that will contain the definitions of the typed dataset and any included DataTable objects. While this demo will only use the Northwind Employees table, you might want add other DataTable definitions later, so name the file Northwind and click the Open button.

  5. At this point a script will run that will generate the file containing the typed dataset information. It's important to realize that this script might trigger a response from your anti-virus software. If that is the case, just select the option to allow the script to run. The Visual Studio .NET Output window will display the progress of the script.

  6. When a typed dataset file is generated, an XSD file (XML Schema Definition) file is created to describe the dataset. This file is automatically opened upon the creation of the typed dataset (Figure 6-6) in a window that is sometimes called a canvas. Database entities can be added to the dataset by dragging them from the Server Explorer onto the canvas, so at this point, click the canvas's Server Explorer link (also available from the Project menu).

    06fig06.jpgFigure 6-6. A drop-target canvas is used to visually represent a typed dataset.

  7. If the desired database is on your local machine, simply browse to that database using the Server Explorer tree view. However, if your database is on a remote machine, you'll need to click the Connect to Server button at the top of the Server Explorer dialog. When the Add Server dialog is displayed, simply type the name of the server. (There's no need to add the UNC path information.)

  8. At this point, you should have a database displayed in the Server Explorer—local or remote. Figure 6-7 shows my particular configuration. As you can see, JEANVALJEAN is the name of my programmer machine, and it has no SQL Server databases. Therefore, I added (connected to) a server named FANTINE to my Server Explorer so that I could access its SQL Server databases.

    06fig07.jpgFigure 6-7. The Server Explorer allows you to drag database entities—such as tables, views, and stored procedures—onto the typed dataset view.

  9. While the icons next to the various databases include an "x", once you expand the item the Server Explorer connects to the database and retrieves the selected database's information—such as its Tables, Views, Stored Procedures, and so on. Here you would simply drag the desired database entity to the dataset palette. For purposes of this demo—and so we can make an "apples and apples" comparison between the untyped datasets you've been using throughout the chapter and a typed dataset—drag the Employees table from the Northwind database to the typed dataset canvas.

  10. If you open the Northwind.h file, you won't see any Employee DataTable information. That information isn't generated until you build the project. Building the project now will result in Visual Studio .NET generating the expected classes and members in the Northwind.h file for the Employees table.

A tremendous amount of code is actually generated for a typed dataset, so we'll just briefly look at some of it—but enough so that you get an idea of what all has been done for you. When you open the Northwind.h file, the first thing you notice is that the file is free-standing in that the appropriate #using and using namespace directives have been inserted. Also note that the typed dataset classes have been defined within a namespace of the same name as the current project. That means you'll have to either qualify all uses of the types defined in this file or insert a using namespace directive into any of your typed dataset client code.

The first class that you encounter will be the DataSet-derived Northwind class. This class also defines nested classes for the Employees table that include a DataTable-derived class, a DataRow-derived class, and a delegate for subscribing to row-change events.

public __gc class Northwind : public System::Data::DataSet {
  public : __gc class EmployeesDataTable;
  public : __gc class EmployeesRow;
  public : __gc class EmployeesRowChangeEvent;
  ...

You'll note that the file does not include any connection-specific information as you might expect. This is so that the typed dataset can be used against any connection. Therefore, the typed dataset only refers to the data entity's schema—not to where the underlying data store is located or how to connect to it. Therefore, the way you would use these types is to connect and build a data adapter just as you would with an untyped dataset, and then use the typed DataSet-derived and DataTable-derived classes as follows.

#include "Northwind.h"
   using namespace System::Data::SqlClient;
   using namespace TypedDataSetDemo;
   
   ...
   
   SqlConnection* conn =
   new SqlConnection(S"Server=FANTINE;"
   S"Database=Northwind;"
   S"Integrated Security=true;");
   SqlDataAdapter* adapter =
   new SqlDataAdapter(S"SELECT * FROM Employees", conn);
   SqlCommandBuilder* commandBuilder = new SqlCommandBuilder(adapter);
   conn->Open();
   Northwind* northwind = new Northwind();
   adapter->Fill(northwind, S"Employees");
   conn->Close(); // No longer needed
   Northwind::EmployeesDataTable* employees = northwind->Employees;
   
   ...
   

Let's look at this code—especially in comparison to the connection code used previously in this chapter using untyped datasets. Obviously, I need to include the Northwind.h file, as it defines the typed dataset types. After that, I need to specify the System::Data::SqlClient namespace, as the Northwind.h file is using generic base classes and the SqlClient namespace is specific to SQL Server ADO.NET types. Finally, the TypedDataSetDemo namespace is referenced so that we don't have to qualify the references to the various typed dataset types.

After the standard connection object creation and instantiation of a data adapter object, I declare an instance of the DataSet-derived Northwind class. From there, I call the adapter's Fill method. However, note that I've changed my table name from the "AllEmployees" value that I've used throughout the chapter to "Employees". While seemingly trivial, I'm actually forced to do this because the Northwind::Employees property is hard-coded to return an EmployeesDataTable object with a name of "Employees".

One last thing that I'll point out before you see a demo illustrating how to use a typed dataset in an MFC application is that no DataRowCollection-derived class is generated for us. This is because the EmployeesDataTable implements the IEnumerable interface and acts as a collection for its rows. The various collection classes, the IEnumerable interface, and even creating your own enumerable classes are covered in Chapter 11. The EmployeesDataTable also implements the Count and Item properties so that an EmployeesDataTable object can be iterated like an array.

public :
[System::Diagnostics::DebuggerStepThrough]
__gc class EmployeesDataTable :
  public System::Data::DataTable,
  public System::Collections::IEnumerable
   {
   
   ...
   
   __property System::Int32 get_Count();
   
   ...
   
   public:
   __property TypedDataSetDemo::Northwind::EmployeesRow* get_Item(
   System::Int32 index
   
   );
   

Because these properties have been implemented, the EmployeesDataTable can be enumerated as simply as this:

...

// For every employee record
for (int i = 0; i < employees->Count; i++)
   {
   int id = *dynamic_cast<__box int*>(employees->Item[i]->EmployeeID);
   String* firstName = employees->Item[i]->FirstName;
   String* lastName = employees->Item[i]->LastName;
   }
   

As you can see, each row is retrieved via the Item property, and, as the row is a Northwind::EmployeesRow, there are properties with the same names and types as the actual Employees table:

public : [System::Diagnostics::DebuggerStepThrough]
__gc class EmployeesRow : public System::Data::DataRow {

...

public: __property System::Int32 get_EmployeeID();
   public: __property  void set_EmployeeID(System::Int32 value);
   public: __property System::String*  get_LastName();
   public: __property  void set_LastName(System::String*_u32 ?value);
   public: __property System::String*  get_FirstName();
   public: __property  void set_FirstName(System::String*  value);
   
   ...
   

Using Typed Datasets

Now let's see how to use typed dataset types in an MFC demo. We'll keep the application simple, as it will connect to the Employees table, read all the employee records, and display them in a list view. However, combining what you'll see here with what you've learned throughout the chapter should make it easy for you to use typed datasets for all your dataset needs should you decide to go that route.

  1. To get started, create and MFC SDI application called TypedDataSetDemo, setting the view base class to CListView and updating the Project settings to support Managed Extensions.

  2. As explained in the previous section, create a typed dataset called Northwind and add to it the Employees table.

  3. Add the following directives to the stdafx.h file:

    #using <mscorlib.dll>
    #using <system.dll>
    #using <system.windows.forms.dll>
    using namespace System;
    using namespace System::Windows::Forms;
    #undef MessageBox
    
  4. Open the TypedDataSetDemoView.h file and add the following directives just before the CTypedDataSetDemoView class declaration.

    #include "Northwind.h"
    using namespace System::Data::SqlClient;
    using namespace TypedDataSetDemo;
    
  5. Declare the following ADO.NET objects in the CTypedDataSetDemoView class.

    class CTypedDataSetDemoView : public CListView
    {
    ...
    protected:
                gcroot<Northwind*>northwind;
                gcroot<SqlDataAdapter*>adapter;
                gcroot<Northwind::EmployeesDataTable*>employees;
                gcroot<SqlCommandBuilder*>commandBuilder;
                ...
                
  6. Add the following code to the view's OnInitialUpdate function to initialize the list view.

    void CTypedDataSetDemoView::OnInitialUpdate()
    {
       CListView::OnInitialUpdate();
      // Add columns to listview
                CListCtrl& lst = GetListCtrl();
                lst.InsertColumn(0, _T("ID"));
                lst.InsertColumn(1, _T("First Name"));
                lst.InsertColumn(2, _T("Last Name"));
                ...
                
  7. In the view class's PreCreateWindow function, set the view window's style to "report":

    BOOL CTypedDataSetDemoView::PreCreateWindow(CREATESTRUCT& cs)
    {
      cs.style |= LVS_REPORT;
                return CListView::PreCreateWindow(cs);
                }
                
  8. Insert the following code just before the end of the OnInitialUpdate function.

    #pragma push_macro("new")
    #undef new
    try
      {
        SqlConnection* conn =
          new SqlConnection(S"Server=localhost;"
                            S"Database=Northwind;"
                            S"Integrated Security=true;");
        adapter = new SqlDataAdapter(S"SELECT * FROM Employees",
                                     conn);
        commandBuilder = new SqlCommandBuilder(adapter);
        conn->Open();
        northwind = new Northwind();
        adapter->Fill(northwind, S"AllEmployees");
        conn->Close(); // No longer needed
        employees = northwind->Employees;
        ReadAllEmployees();
      }
      catch(Exception* e)
      {
        MessageBox::Show(e->Message,
                         S".NET Exception Thrown",
                         MessageBoxButtons::OK,
                         MessageBoxIcon::Error);
      }
    #pragma pop_macro("new")
    
  9. Finally, implement the ReadAllEmployees function as follows:

    void CTypedDataSetDemoView::ReadAllEmployees()
    {
      try
      {
        CWaitCursor wc;
        CListCtrl& lst = GetListCtrl(); lst.DeleteAllItems();
        for (int i = 0; i < employees->Count; i++)
        {
          int idx = lst.InsertItem(i,
            (CString)__box(employees->Item[i]->EmployeeID)->
              ToString());
          lst.SetItemText(idx, 1,
            (CString)employees->Item[i]->FirstName);
          lst.SetItemText(idx, 2,
            (CString)employees->Item[i]->LastName);
        }
      }
      catch(Exception* e)
      {
        MessageBox::Show(e->Message, S".NET Exception Thrown",
                         MessageBoxButtons::OK,
                         MessageBoxIcon::Error);
      }
    }
    

Building and running the application will result in something similar to what you see in Figure 6-8. The code in this section was really not much different than what you've seen throughout this chapter, with the principal difference being that the use of typed dataset types enabled you to have the compiler check for common errors as opposed to having them realized at runtime. This segues nicely into the next part of this chapter—weighing the pros and cons of using typed datasets.

06fig08.gifFigure 6-8. Example of running the TypedDataSetDemo application

Weighing the Pros and Cons of Typed Datasets

Covering the entirety of typed datasets would take an entire chapter by itself. However, you've learned enough about typed datasets in this section to realize some of the positive points regarding using them in your ADO.NET code. Let's now briefly look at some of the advantages and disadvantages of using typed datasets (vs. using untyped datasets).

Advantages of typed datasets:

  • Compile-time type checking— Reduces runtime errors by having members based on the data's actual schema as opposed to untyped datasets, where you call a generic function and can pass an object of any type.

  • Schema-specific members— Typed datasets define properties for getting and setting values where the property name is the same as the underlying column name. They also define properties for determining if the column is null and methods for searching the table via primary key(s).

  • Data binding support in VS.NET— Only useful with Windows Forms applications, but bears mentioning if you plan on doing development based entirely on .NET in addition to the mixed-mode programming that is the focus of this book.

  • Intellisense support— When using untyped datasets, you have to know beforehand the names of the columns and the types that the respective columns work with. With typed datasets, as soon as you enter the name of the type, Intellisense displays its members, thereby saving you development and debugging time.

Disadvantages of typed datasets:

  • Versioning— Typed datasets can actually increase development time in situations where your schema changes, because you'll need to update the typed dataset information manually. This is obviously the same problem we've battled for years with CRecordset classes—having to modify them manually when the underlying schema changes.

  • Tightly coupled— In its current design, typed datasets are difficult to extend and can't be modified (as they're auto-generated each time the project is built). In addition, they force a tight coupling of client to data access code, which might not be best for all situations.

As mentioned earlier in the chapter, I use untyped datasets in code snippets and demos, as this provides for shorter, to-the-point code listings. However, I personally choose to use typed datasets in my production code, as once I'm to the implementation stage of a project, I'm finished with any major changes to the database schema, and with the introduction of dataset annotations, the only two real disadvantages for me are moot. (Annotations are extensions to the XSD format used to define typed datasets that allow some changes such as the renaming of classes and properties as well as defining how to deal with null values.)

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