使用自动映射器从键值对映射值

时间:2019-03-02 00:52:41

标签: c# automapper

对于问题标题不清楚,我深表歉意。我将尝试用简单的词来解释:

我正在使用指定的映射在函数内部创建一个Mapper实例:

//omitted rest of the mapping to make the code simpler 
private TRADELINE MapTradeLine(Tradeline tradeLine, TradelineMeta tradelineMeta)
{
    MapperConfiguration configMapTradeline = new MapperConfiguration(
     cfg =>
     {
         cfg.CreateMap<Tradeline, TRADELINE>()       
         .ForPath(dest => dest.TLSOURCE, opt => opt.MapFrom(src => src.Source))              
         .ForPath(dest => dest.REQID, opt => opt.MapFrom(src => tradelineMeta.RequestId))        
     });
    IMapper mapperTradeline = configMapTradeline.CreateMapper();    
    return mapperTradeline.Map<Tradeline, TRADELINE>(tradeLine);
}

这很好。虽然想将此代码移至Profile

类似这样的东西:

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        .CreateMap<Tradeline, TRADELINE>()       
         .ForPath(dest => dest.TLSOURCE, opt => opt.MapFrom(src => src.Source))              
         .ForPath(dest => dest.REQID, opt => opt.MapFrom(src => tradelineMeta.RequestId));
    }
}

public static class MappingHelper
{
    private static readonly Lazy<IMapper> Lazy = new Lazy<IMapper>(() =>
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
            cfg.AddProfile<MappingProfile>();
        });
        var mapper = config.CreateMapper();
        return mapper;
    });

    public static IMapper Mapper => Lazy.Value;
}

之后,我可以使用IMapper实例执行映射。我的目标是避免为每个方法调用初始化AutoMapper。

如果坚持使用tradelineMeta.RequestId方法,我会坚持如何指定Profile

有可能吗?

1 个答案:

答案 0 :(得分:0)

如@Lucian Bargaoanu提供的linkthis问题中所述,我能够弄清楚:

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        .CreateMap<Tradeline, TRADELINE>()       
         .ForPath(dest => dest.TLSOURCE, opt => opt.MapFrom(src => src.Source))                       
         .ForMember(dest => dest.REQID, opt => opt.MapFrom((src, dest, destMember, context) => context.Items["REQID"]))
    }
}

用法:

return MappingHelper.Mapper.Map<Tradeline, TRADELINE>(tradeLine, opt =>
     {                 
         opt.Items["REQID"] = tradelineMeta.RequestId;                 
     });