c# – Automapper – ReverseMap()不执行映射

我有以下两个班级:

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 / Id和Horsepower / 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-> TDestination和TDestination-> TSource映射?我认为ReverseMap的目的是避免我们手动指定双向映射.

解决方法:

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

Mapper.CreateMap<Engine, ReferenceEngine>();

Mapper.CreateMap<ReferenceEngine, Engine>();

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

上一篇:c# – 使用AutoMapper的IMappingEngine和DI有什么好处(如果有的话)


下一篇:c# – AutoMapper将2个表中的记录连接到单个IEnumerable视图模型中