Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper - ReverseMap() does not perform mapping

Tags:

c#

automapper

I have the following 2 classes:

public class ReferenceEngine
{
    public Guid ReferenceEngineId { get; set; }
    public string Description { get; set; }
    public int Horsepower { get; set; }
}

public class Engine
{
    public Guid Id { get; set; }
    public string Description { get; set; }
    public int Power { get; set; }
}

I am using automapper to perform a mapping from ReferenceEngine to Engine and vice versa. Notice that the properties ReferenceEngineId/Id and Horsepower/Power does not have the same name.

The following mapping configuration works and the properties having different names are successfully mapped:

public static void ConfigureMapperWorking()
{
    AutoMapper.Mapper.CreateMap<ReferenceEngine, Engine>()
        .ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Description)).ReverseMap();

    AutoMapper.Mapper.CreateMap<ReferenceEngine, Engine>()
        .ForMember(dest => dest.Id, opt => opt.MapFrom(src => Guid.Parse(src.ReferenceEngineId.ToString())))
        .ForMember(dest => dest.Power, opt => opt.MapFrom(src => src.Horsepower));

    AutoMapper.Mapper.CreateMap<Engine, ReferenceEngine>()
        .ForMember(dest => dest.ReferenceEngineId, opt => opt.MapFrom(src => Guid.Parse(src.Id.ToString())))
        .ForMember(dest => dest.Horsepower, opt => opt.MapFrom(src => src.Power));
}

However the following does not work although I invoke the method ReverseMap() at the end:

public static void ConfigureMapperNotWorking()
{
    AutoMapper.Mapper.CreateMap<ReferenceEngine, Engine>()
        .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.ReferenceEngineId))
        .ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Description))
        .ForMember(dest => dest.Power, opt => opt.MapFrom(src => src.Horsepower)).ReverseMap();
}

My question is, when property names are different, should we manually specify the TSource->TDestination and TDestination->TSource mapping? I thought the purpose of the ReverseMap is to avoid us from manually specifying the bi-directional mapping.

like image 409
Ashish Avatar asked Sep 26 '22 07:09

Ashish


1 Answers

ReverseMap only creates a simple reverse mapping. For example it would automatically configure

Mapper.CreateMap<Engine, ReferenceEngine>();

from

Mapper.CreateMap<ReferenceEngine, Engine>();

To get anything more complex, you have to configure it manually.

like image 126
jlvaquero Avatar answered Sep 30 '22 07:09

jlvaquero