I have a few models that I would like to map using AutoMapper. Automapper is set to map from an IDataReader to the model class. The issue is that I need to have a ITypeConverter set on my mapper so that I can enumerate a limited amount of times for each model. I don't want to create many classes inheriting from ITypeConverter for every model.
Example Model:
public class Customer: IModel
{
public FirstName { get; set; }
public LastName { get; set; }
}
Mapper Class:
public static class AutoMappingConfig
{
public static void Configure()
{
// I would have many other mappings like the one below. All taking an IDataReader and mapping to a model inheriting from IModel
Mapper.CreateMap<IDataReader, Customer>()
.ForMember(x => x.FirstName, o => o.MapFrom(s => s.GetString(s.GetOrdinal("first_name")))
.ForMember(x => x.LastName, o => o.MapFrom(s => s.GetString(s.GetOrdinal("last_name"))));
// I would have many of the following. All taking an IDataReader and mapping to an IEnumerable model object
Mapper.CreateMap<IDataReader, IEnumerable<Customer>>().ConvertUsing<ModelConverter<Customer>>();
}
}
Converter:
public class ModelConverter<T>: ITypeConverter<IDataReader, IEnumerable<T>> where T: IModel
{
public IEnumerable<T> Convert(ResolutionContext context)
{
var dataReader = (IDataReader) context.SourceValue;
var rowCount = 0;
var collection = new List<T>();
// The purpose for this ModelConverter is the a maximum row count of 10
while (dataReader.Read() && rowCount < 10)
{
var item = Mapper.Map<IDataReader, T>(dataReader);
collection.Add(item);
rowCount++;
}
return collection;
}
}
Note: The problem is not with the ModelConverter class as it never gets called when I pass in an IDataReader. I have attempted a similar mapping system with another class and it gets called and processes the mapping successfully.
When I run the following code, the value being returned is a list of items with null mappings. The ModelConverter class does not get called at all. The above code works for any input other than IDataReader. AutoMapper is doing something special with the IDataReader but I am not sure how to proceed with the ITypeConverter at this point.
var customers = Mapper.Map<IDataReader, IEnumerable<Customer>>(dataReader);
In the above code, dataReader is the IDataReader object.