gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:33:31 25 4
gpt4 key购买 nike

我有以下两个类:

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

最佳答案

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

Mapper.CreateMap<Engine, ReferenceEngine>();

来自

Mapper.CreateMap<ReferenceEngine, Engine>();

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

关于c# - Automapper - ReverseMap() 不执行映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33560936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com