Create the DataTableMapping Method

Purpose:

To create a method that will return an object that will be used to map data returned from the data base.  All dataset operations require a DataTableMapping.

Starting Point:

You have VisualStudio.NET open.  You are creating the RegionHelper command class in the Data Access project.  The code generated by the Data Adapter Wizard while it was generating the stored procedures for the Region table should be readily available.

Steps:                                                

  1. Just below the default constructor, declare a function of type DataTableMapping (System.Data.Common.DataTableMapping to be precise).
  2. Declare a local variable also of type DataTableMapping and initialize it to new DataTableMapping using the same parameters used in the DataTableMapping initialization in the wizard-generated code (“Table”, “Region”).
  3. Note in the wizard-generated code that there is one DataColumnMapping for each field in the table.  We will add a ColumnMapping to our newly created local DataTableMapping using slightly different syntax.
  4. Add one ColumnMapping object for each column in the table using your local DataTableMapping object’s ColumnMappings.Add method.  The column names and their output equivalents are in the DataTableMapping declaration in the wizard-generated code.
  5. Return the newly constructed DataTableMapping object.  The code for this method should now look something like this:

    public DataTableMapping theDataTableMapping()
    {
          DataTableMapping thisDTM = new DataTableMapping("Table", "Region");
          thisDTM.ColumnMappings.Add("RegionID", "RegionID");
       thisDTM.ColumnMappings.Add("RegionDescription", "RegionDescription");
          return thisDTM;
    }
  6. Compile and save.

Rationale:

You need a Data Table Mapping whenever want to use a data set and a data adapter.  This provides a common, accurate map for the underlying object with little work.  Furthermore, this method is not prone to the kinds of errors that are common to building data table mappings.

Discussion:

The first parameter in the ColumnMappings.Add method names the source column; the second is the name it will have in the returned dataset.  As you can see, the same name is always used unless a source column name is duplicated.

All data table mapping methods should look very similar to this, varying only by the name of the table and the name and number of columns.

Note that this is similar to the rest of the methods in that it converts an object created by the wizard into a widely available object.  It is different from the rest of the methods in that it requires more editing and transformation, and it uses slightly different syntax.

Previous Step: Create the RegionHelper Class

Next Step: Create the Select Command Method