Converting an object collection to a DataSet

time to read 3 min | 462 words

There are many tools that tends to work only with DataSets, the most often cases are reporting tools or data driven systems. I consider this an issue with the tool, usually, but this is a fact of line. Case in point, I want to display a report of customer objects, I say objects here because I retrieve them through an NHibernate query + business logic that can't really be done in a stored procedure.

At the end, I get a collection of customer objects, and I need to pass that to a reporting tool that can only accept a DataSet, this means that I need to translate an object graph to tabular format.

Pay no attention to the man behind the screen!

Here is my secret technique to do this:

DataTable dt = new DataTable();
dt.Columns.Add("CustomerId"typeof(int));
dt.Columns.Add("CustomerName"typeof(string));
dt.Columns.Add("RegisteredAt"typeof(string));//not a typo, sadly.

// ... lot more properties, often nested ones.

foreach(Customer cust in customers)
{
  DataRow row = dt.NewRow();
  row["CustomerId"] = cust.Id;
  row["CustomerName"] = cust.At(reportDate).Name;
  row["RegisteredAt"] = cust.RegisteredAt.ToShortDateString();
  //... lot more properties

  dt.Rows.Add(row);
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;

Sorry that it isn't magic, just the simplest solution that could work without writing a whole new data source adapter for the tool.