When an object-relational mapper is too much, DataReader too little
I fired up Visual Studio this evening to write a proof-of-concept app and found myself wanting strongly typed domain objects from a database but without the overhead of an object-relational mapper (the application is read-only).
One solution is to write methods by hand, another is to code generate them but it would be nice to be able to do:
var customers = new SqlCommand("SELECT ID, Name FROM Customer", connection)
.As(r => new Customer { CustomerID = r.GetInt32(0), Name = r.GetString(1) }).ToList();
So for any DbCommand object you can turn it into a bunch of classes by specifying the new pattern.
The tiny helper class to achieve this is:
public static class DataHelpers {
public static List<T> ToList<T>(this IEnumerable<T> enumerable) {
return new List<T>(enumerable);
}
public static IEnumerable<T> As<T>(this DbCommand command, Func<IDataRecord, T> map) {
using (var reader = command.ExecuteReader())
while (reader.Read())
yield return map(reader);
}
}
It might even be possible to do some cool caching/materialization. I should look into that :)
[)amien
16 responses