Last active
April 3, 2023 15:02
-
-
Save tomchatting/c845e230f4a07e7e7ddb15963e3b5e65 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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