Automapper - ReverseMap()不执行映射

时间:2015-11-06 06:41:38

标签: c# automapper

我有以下两个班级:

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; }
}

我正在使用automapper执行从ReferenceEngine到Engine的映射,反之亦然。请注意,属性ReferenceEngineId / IdHorsepower / Power的名称不同。

以下映射配置有效,并且成功映射了具有不同名称的属性:

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));
}

但是,尽管我在最后调用方法ReverseMap(),但以下方法不起作用:

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();
}

我的问题是,当属性名称不同时,我们是否应该手动指定TSource-&gt; TDestination和TDestination-&gt; TSource映射?我认为ReverseMap的目的是避免我们手动指定双向映射。

1 个答案:

答案 0 :(得分:3)

ReverseMap仅创建一个简单的反向映射。例如,它会自动配置

Mapper.CreateMap<Engine, ReferenceEngine>();

来自

Mapper.CreateMap<ReferenceEngine, Engine>();

要获得更复杂的东西,您必须手动配置它。