1

I want to map a Source object to Destination object which has some extra properties which are not directly equivalent to the source properties. Consider below example:

class Source { string ImageFilePath; }

class Destination { bool IsFileSelected; bool IsFileGif; }

Mapping Logic for IsFileGif:

destinationObj.IsFileGif = Path.GetExtension(sourceObj.ImageFilePath) == ".gif" ? true : false;

Mapping Logic for IsFileSelected:

destinationObj.IsFileSelected = string.IsNullOrEmpty(sourceObj.ImageFilePath) ? false : true;

Also, since my source is an IDataReader, I would wish to know how to map the field/column of an IDataReader object to my Destination property.

Can we achieve this using an inline code or do we have to use Value Resolvers for it ?

Lucifer
  • 2,317
  • 9
  • 43
  • 67

2 Answers2

0

Have you tried using the MapFrom method?

Mapper.CreateMap<Source , Destination>()
 .ForMember(dest => dest.IsFileGif, opt => opt.MapFrom(src => Path.GetExtension(sourceObj.ImageFilePath) == ".gif")
 .ForMember(dest => dest.IsFileSelected, opt =>  opt.MapFrom(src => !string.IsNullOrEmpty(sourceObj.ImageFilePath));

Regarding the IDataReader, I think you should be mapping between your classes (Source to Destination), not from an IDataReader to Destination...

Leandro Gomide
  • 998
  • 1
  • 10
  • 31
  • Thanks @Igomide, the MapFrom method worked. The Source class was simply used for the sake of simplicity. In my real scenario, the source is actually an IDataReader created from a DataTable object retrieved from the database. And I have written a generic extension method that will do the IDataReader -> IEnumerable mapping. – Lucifer Mar 17 '15 at 18:08
0

I figured out mapping from an IDataReader to a Destination object:

Mapper.CreateMap<IDataReader, Destination>()
                    .ForMember(d => d.IsFileSelected,
                         o => o.MapFrom(s => !string.IsNullOrEmpty(s.GetValue(s.GetOrdinal("ImageFilePath")).ToString())))
                    .ForMember(d => d.IsFileGif,
                         o => o.MapFrom(s => Path.GetExtension(s.GetValue(s.GetOrdinal("ImageFilePath")).ToString()) == ".gif"));

Would appreciate if anyone verify's this code or suggest if a better alternative exists.

Lucifer
  • 2,317
  • 9
  • 43
  • 67