Search code examples
.netautomapperidatareader

AutoMapper : Map a destination property to a different source property/type based on some logic


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 ?


Solution

  • 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...