public async Task<DataTable> PopulateDataTable()
{
DataTable dataTable = new DataTable();
using (var conn = new SqlConnection(_configuration.Value))
{
string query = @"<--SQL QUERY HERE-->";
conn.Open();
try
{
var model = await conn.QueryAsync<Model>(query, commandType: CommandType.Text);
if (!model.Any())
{
throw new Exception("No data found.");
}
// Create columns for the DataTable
foreach (var property in typeof(Model).GetProperties())
{
dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}
// Populate DataTable with data
foreach (var item in model)
{
var row = dataTable.NewRow();
foreach (var property in typeof(Model).GetProperties())
{
var value = property.GetValue(item) ?? DBNull.Value;
row[property.Name] = value;
}
dataTable.Rows.Add(row);
}
}
catch (Exception ex)
{
throw ex; // Consider logging the exception
}
finally
{
conn.Close();
}
}
return dataTable;
}