Mapping IDataReader to object without third party libraries

668 Views Asked by At

Are there any quick way to map some IDataReader to object without third party libraries such as AutoMapper or ValueInjecter?

2

There are 2 best solutions below

0
On BEST ANSWER

I'm not sure what you mean by quick, but you can put something together using reflection. There's a lot of assumptions you'll have to make, such as all your object's values are set via properties. And, your DataReader columns MUST match your object property name. But you could do something like this:

NOTE: The SetProperty function is from an article on DevX. (It was in VB.NET, and I converted it to C# -- if there are mistakes, I probably 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 a reference to the PropertyInfo, exit if no property with that 
        //name
        System.Reflection.PropertyInfo pi = obj.GetType().GetProperty(propertyName);
        if (pi == null) then return false;
        //convert the value to the expected type
        val = Convert.ChangeType(val, pi.PropertyType);
        //attempt the assignment
        pi.SetValue(obj, val, null);
        return true;
    }
    catch {
        return false;
    }
}

No guarantees that this code will run (I'm just typing it and not compiling/testing it), but it at least may be a start.

I've done things like this in the past and have gotten fancy with applying attributes to my properties stating what data reader column to map to the property. Too much to include here, but this is just a starter and hopefully is what you're looking for.

Hope this helps!

1
On

Sure,

class MyObject
{
    public string SomeProperty { get; set; }
    public MyObject(IDataReader reader)
    {
        SomeProperty = reader.GetString(0);
        // - or -
        SomeProperty = reader.GetString(reader.GetOrdinal("SomeProperty"));
        // etc.
    }
}