c# - Mapping IDataReader to object without third party libraries -


are there quick way map idatareader object without third party libraries such automapper or valueinjecter?

i'm not sure mean quick, can put using reflection. there's lot of assumptions you'll have make, such object's values set via properties. and, datareader columns must match object property name. this:

note: setproperty function article on devx. (it in vb.net, , converted c# -- if there mistakes, missed something.)

ilist<myobject> myobjlist = new list<myobject>();  while (reader.read()){   int fieldcount = reader.fieldcount;   myobject myobj = new myobject();   for(int i=0;i<fieldcount;i++){     setproperty(myobj, reader.getname(i), reader.getordinal(i));   }   myobjlist.add(myobj); }  bool setproperty(object obj, string propertyname, object val) {     try {         //get reference propertyinfo, exit if no property          //name         system.reflection.propertyinfo pi = obj.gettype().getproperty(propertyname);         if (pi == null) return false;         //convert value expected type         val = convert.changetype(val, pi.propertytype);         //attempt assignment         pi.setvalue(obj, val, null);         return true;     }     catch {         return false;     } } 

no guarantees code run (i'm typing , not compiling/testing it), @ least may start.

i've done things in past , have gotten fancy applying attributes properties stating data reader column map property. include here, starter , you're looking for.

hope helps!


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -