A while ago, I submitted a patch to AutoMapper that added basic support for mapping data from an IDataReader/IDataRecord to an object. For those of us who don't have the luxury to use NHibernate in their projects, this feature can save you from writing lots of repetitive and tedious code.
Its usage is pretty much the same as with regular object-to-object mapping using AutoMapper. Lets show a very simple example.
Suppose we have a view object like the one shown below:
Now when we can execute a query like this,
and read the results using a data reader. Now we can use AutoMapper to map the results to instances of our view class:
This results in a collection of one of or more view objects. When our query is guaranteed to always return one record, we can use the following syntax:
This approach expects that a convention is followed whereby the name of a field returned by the query matches the name of a property on the target class. Its also possible to use projection as already provided for regular object-to-object mapping.
Suppose we add a new property to our view,
and we modify the query so that we retrieve the corresponding date value from the database:
Notice that we've broken the convention here and we need to use projection to ensure that the retrieved date value is mapped to the correct property.
public class SomeView
{
public Int32 SomeNumber { get; private set; }
public Guid AnId { get; private set; }
public Double OrNothing { get; private set; }
}
Using projection we're able to manually map from a data reader or data record. In some sense, we're back to square one if we have to do this for all fields. Trying to follow the convention is of course the most useful.
I know it's not much, but I think it can be helpful for those cases where you actually need to map from a data reader or a data record to an object.