Created
July 9, 2010 16:53
-
-
Save amarraja/469701 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* Simple utility to take some of the pain of working with a datareader */ | |
public static class DataReaderExtensions | |
{ | |
public static IList<T> ToTypedList<T>(this SqlDataReader dr) where T : class, new() | |
{ | |
var list = new List<T>(); | |
if (!dr.HasRows) | |
return list; | |
var propertyMap = new Dictionary<string, PropertyInfo>(); | |
for (int x = 0; x < dr.FieldCount; x++) | |
{ | |
string columnName = dr.GetName(x); | |
var property = typeof (T).GetProperties() | |
.Where(t => t.Name.Equals(columnName, StringComparison.OrdinalIgnoreCase)) | |
.SingleOrDefault(); | |
if (property != null) | |
{ | |
propertyMap.Add(columnName, property); | |
} | |
} | |
while(dr.Read()) | |
{ | |
T t = new T(); | |
foreach (var propertyInfo in propertyMap) | |
{ | |
object columnValue = dr[propertyInfo.Key]; | |
if (columnValue != DBNull.Value) | |
propertyInfo.Value.SetValue(t, columnValue, null); | |
} | |
list.Add(t); | |
} | |
return list; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment