I came up with the following solution using the concept of ResultTransformer described here:
public class DataTableResultTransformer : IResultTransformer
{
private DataTable dataTable;
public IList TransformList(IList collection)
{
var rows = collection.Cast<DataRow>().ToList();
rows.ForEach(dataRow => dataTable.Rows.Add(dataRow));
return new List<DataTable> { dataTable };
}
public object TransformTuple(object[] tuple, string[] aliases)
{
//Create the table schema based on aliases if its not already done
CreateDataTable(aliases);
//Create and Fill DataRow
return FillDataRow(tuple, aliases);
}
private DataRow FillDataRow(object[] tuple, string[] aliases)
{
DataRow dataRow = dataTable.NewRow();
aliases.ToList().ForEach(alias =>
{
dataRow[alias] = tuple[Array.FindIndex(aliases, colName => colName == alias)];
});
return dataRow;
}
private void CreateDataTable(IEnumerable<string> aliases)
{
if (dataTable == null)
{
dataTable = new DataTable();
aliases.ToList().ForEach(alias => dataTable.Columns.Add(alias));
}
}
}
And use it as following:
using (ISession session = sessionFactory.OpenSession())
{
var sqlQuery = session.CreateSQLQuery("SELECT ID, NAME, ADDRESS FROM CUSTOMER");
var transformedQuery = sqlQuery.SetResultTransformer(new DataTableResultTransformer());
return transformedQuery.List().Single();
}
I have just created a custom ResultTransformer and use it in my sql query to transform the result of the query based on my logic in the DataTableResultTransformer.
The TransformTupple method is called for each item in the result set. The tuple contains the data where as the aliases contain the names for the data. So, we have almost everything to build and fill our DataTable. Once all the items of the result set have been transformed by the TransformTupple method then the TransformList method is called at the end. The collection parameter contains all items that we transformed into DataRow in TransformTupple method. So, here we can easily fill our DataTable with the DataRows and return.
Hope its helpful for others dealing with same kind of scenario.