Skip to content

Instantly share code, notes, and snippets.

@tomchatting
Last active April 3, 2023 15:02
Show Gist options
  • Save tomchatting/c845e230f4a07e7e7ddb15963e3b5e65 to your computer and use it in GitHub Desktop.
Save tomchatting/c845e230f4a07e7e7ddb15963e3b5e65 to your computer and use it in GitHub Desktop.
/*
* MapToClass provides a function for the C# SQL datareader, allowing you to automatically
* map output from a SQL query to a class
*
* I found this on SO a few weeks ago and I cannot for the life of me find it again
* so I'll pop it here and add attribution when I find the link buried in my history
*
* This means you can spend less time doing this:
* while (dr.Read())
* {
* string strFilterName = dr["Column1"].ToString();
*/
// Step one - add MapToClass
T MapToClass<T>(SqlDataReader reader) where T : class
{
T returnedObject = Activator.CreateInstance<T>();
PropertyInfo[] modelProperties = returnedObject.GetType().GetProperties();
for (int i = 0; i < modelProperties.Length; i++)
{
MappingAttribute[] attributes = modelProperties[i].GetCustomAttributes<MappingAttribute>(true).ToArray();
if (attributes.Length > 0 && attributes[0].ColumnName != null)
modelProperties[i].SetValue(returnedObject, Convert.ChangeType(reader[attributes[0].ColumnName], modelProperties[i].PropertyType), null);
}
return returnedObject;
}
// Step two - add SQL row names to your class
public class Chart
{
[Mapping(ColumnName = "Performance_ID")]
public string performanceID { get; set; }
[Mapping(ColumnName = "RowID")]
public int rowID { get; set; }
[Mapping(ColumnName = "ChartID")]
public int chartID { get; set; }
[Mapping(ColumnName = "Date")]
public DateTime date { get; set; }
}
// Step three - profit!
using (SqlDataReader reader = dr)
{
while (reader.Read()) {
chart = MapToClass<Chart>(reader);
chartData.Add(chart);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment