Automapper - ReverseMap() does not perform mapping

2019-06-28 04:00发布

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.

标签: c# AutoMapper
1条回答
▲ chillily
2楼-- · 2019-06-28 04:58

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.

查看更多
登录 后发表回答