How can I map a DataReader object into a class object by using generics?
For example I need to do the following:
public class Mapper
{
I don't think you'll be able to get around defining the relationship between fields in some form. Take a look at this article and pay particular attention to how the mapping is defined, it may work for you.
http://www.c-sharpcorner.com/UploadFile/rmcochran/elegant_dal05212006130957PM/elegant_dal.aspx
I use ValueInjecter for this
I'm doing like this:
while (dr.Read())
{
var o = new User();
o.InjectFrom<DataReaderInjection>(dr);
yield return o;
}
you gonna need this ValueInjection for this to work:
public class DataReaderInjection : KnownSourceValueInjection<IDataReader>
{
protected override void Inject(IDataReader source, object target, PropertyDescriptorCollection targetProps)
{
for (var i = 0; i < source.FieldCount; i++)
{
var activeTarget = targetProps.GetByName(source.GetName(i), true);
if (activeTarget == null) continue;
var value = source.GetValue(i);
if (value == DBNull.Value) continue;
activeTarget.SetValue(target, value);
}
}
}
What about using Fluent Ado.net ?
The easiest way I can think of offhand would be to supply a Func<T,T>
delegate for converting each column and constructing your book.
Alternatively, if you followed some conventions, you could potentially handle this via reflection. For example, if each column mapped to a property in the resulting object using the same name, and you restricted T in your Mapper to providing a constructable T, you could use reflection to set the value of each property to the value in the corresponding column.
Well, i don't know if it fits here, but you could be using the yield keyword
public static IEnumerable<T> MapObject(IDataReader dr, Func<IDataReader, T> convertFunction)
{
while (dr.Read())
{
yield return convertFunction(dr);
}
}
I would recommend that you'd use AutoMapper for this.