Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - IDataReader to Object mapping using generics

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<T>
    {
        public static List<T> MapObject(IDataReader dr)
        {
            List<T> objects = new List<T>();

            while (dr.Read())
            {
                //Mapping goes here...
            }

            return objects;
        }
    }

And later I need to call this class-method like the following:

IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book");

List<Book> bookList = Mapper<Book>.MapObject(dataReder);

foreach (Book b in bookList)
{
     Console.WriteLine(b.ID + ", " + b.BookName);
}

Note that, the Mapper - class should be able to map object of any type represented by T.

like image 735
user366312 Avatar asked Jul 09 '09 18:07

user366312


2 Answers

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);
            }
        }
    }
like image 73
Omu Avatar answered Sep 20 '22 16:09

Omu


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);
            }
        }
like image 38
Jhonny D. Cano -Leftware- Avatar answered Sep 18 '22 16:09

Jhonny D. Cano -Leftware-