Converting DataSets to Strongly-Typed DataSets

One of the first things shown to me when I started working in my company was Microsoft’s Data Access Application Block. One thing that bothered me was that I constantly had to convert DataSets it returned to strongly typed DataSets used in our programs, which usually meant merging the returned data set with a newly created DataTable. To relieve myself of those repeating tedious 6 lines of code, I made this little class that converts untyped DataSets and DataTables to a strongly typed DataTable.
In a first attempt to solve this problem, I used reflation to create an instance of the typed DataTable, so I had to pass the method the type of the DataTable, and cast it back to itself.
This is a more elegant solution, using generics:

/// <summary>
/// Helper methods and functions.
/// </summary>
/// <typeparam name="T">A strongly type DataTable.
/// A DataTable of type T will be returned from the DataSet.
/// </typeparam>
public static class DataSetAdapter<T>
                          where T : DataTable, new()
{
    /// <summary>
    /// Convert the first DataTable from a DataSet to a
    /// strongly-typed data table.
    /// </summary>
    public static T convert(DataSet dataSet)
    {
        if (dataSet == null)
            return null;
        if (dataSet.Tables.Count == 0)
            return null;
        DataTable dataTable = dataSet.Tables[0];
        return convert(dataTable);
    }
    /// <summary>
    /// Convert an ordinary DataTable to a strongly-typed
    /// data table.
    /// </summary>
    public static T convert(DataTable dataTable)
    {
        if (dataTable == null)
            return null;
        T stronglyTyped = new T();
        // add data from the regular DataTable to the
        // strongly typed DataTable.
        stronglyTyped.Merge(dataTable);
        return stronglyTyped;
    }
}

The use of the class if pretty straightforward, just pass the DataSet and the Type:

DataSet employeesDataSet = OracleHelper.ExecuteDataset(
 connectionString, storedProcedure, parameters);
EmployeesDataTable employees =
 DataSetAdapter<EmployeesDataTable>.convert(employeesDataSet);

Links:

1 thought on “Converting DataSets to Strongly-Typed DataSets

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.