Posted by
pieterg on
3/9/2010 7:37 AM |
Comments (44)
So, I recently had the chance to quickly write some code that gave me the ability to quickly get data from the database.
I didn’t like the naming of the columns so I came up with an Attribute ColumnMapping that has UIName and DBName properties and here is the method to retrieve the data
/// Context Mapper that takes an Attribute and maps it from the stored procedure
///
///
public static class ContextMapper<T> where T : new()
{
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
///
/// Get Data Maps the data from a Stored Procedure result to a Type
///
///
///
public static List GetData(StoredProcedure storedProcedure)
{
List results = new List();
DbDataReader dbReader = storedProcedure.ExecuteReader();
while (dbReader.Read())
{
T result = new T();
PropertyInfo[] propertyInfos = typeof(T).GetProperties();
foreach (PropertyInfo propInfo in propertyInfos)
{
int? ordinal = null;
try
{
ordinal = dbReader.GetOrdinal((propInfo.GetCustomAttributes(typeof(ColumnMapping), false)[0] as ColumnMapping).ColumnName);
}
catch (IndexOutOfRangeException ex)
{
//Couldn't find ordinal, probably doesn't exist in the collection
logger.Warn(ex.Message, ex);
}
if (ordinal != null)
{
if (propInfo.GetCustomAttributes(typeof(ColumnMapping), false).Count() && !dbReader.IsDBNull(dbReader.GetOrdinal((propInfo.GetCustomAttributes(typeof(ColumnMapping), false)[0] as ColumnMapping).ColumnName)))
{
propInfo.SetValue(result, dbReader[(propInfo.GetCustomAttributes(typeof(ColumnMapping), false)[0] as ColumnMapping).ColumnName], null);
}
}
}
results.Add(result);
}
return results;
}
}
89636726-936f-45c1-b90e-cee6e6d0b07a|0|.0