Automapper - ReverseMap() does not perform mapping

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

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.

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!