本文介绍了Automapper-ReverseMap()不执行映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下2个课程:

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

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

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

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

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

我的问题是,当属性名称不同时,是否应该手动指定TSource-> TDestination和TDestination-> TSource映射?我认为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.

推荐答案

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

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

Mapper.CreateMap<Engine, ReferenceEngine>();

来自

Mapper.CreateMap<ReferenceEngine, Engine>();

要使事情变得更复杂,您必须手动进行配置.

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

这篇关于Automapper-ReverseMap()不执行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:49