简体   繁体   English

基于变量的自动映射器中的映射

[英]Mapping in automapper based on a variable

I am using Automapper for mapping my dtos.我正在使用 Automapper 来映射我的 dto。 I have a tricky scenario where I want to map on condition.我有一个棘手的场景,我想在条件下使用 map。

if (countryCode == "")

    CreateMap<src, dest>()                
                .ForMember(dest => dest.CountryOriginCode, 
                            act => act.MapFrom(src => 
                 src.FirstOrDefault(k => k.Key == "CountryExportCode").Value))

else

    CreateMap<src, dest>()                
                .ForMember(dest => dest.CountryOriginCode, 
                            act => act.MapFrom(src => 
                 src.FirstOrDefault(k => k.Key == "CountryOriginCode").Value))

I have 2 requirements here.我在这里有两个要求。

  1. I want to map it conditionally我想有条件地 map
  2. How can I get the value of CountryCode which is in another object say CountryObject如何获取另一个 object 中的 CountryCode 值,比如 CountryObject

Edit -编辑 -

CreateMap<country, countryDto>() CreateMap<国家, countryDto>()
.ForMember(dest => dest.CountryCode, act => act.MapFrom(src => src.CountryCode)) .ForMember(dest => dest.CountryCode, act => act.MapFrom(src => src.CountryCode))

CreateMap<src, dest>()                
.ForMember(
    dest => dest.CountryOriginCode, 
    act => act.MapFrom(src => countryCode == CountryCode ? // Observer the CountryCode , I need it from above 
        src.FirstOrDefault(k => k.Key == "CountryExportCode").Value:
        src.FirstOrDefault(k => k.Key == "CountryOriginCode").Value)
)

How about this这个怎么样

CreateMap<src, dest>()                
    .ForMember(
        dest => dest.CountryOriginCode, 
        act => act.MapFrom(src => countryCode == "" ?
            src.FirstOrDefault(k => k.Key == "CountryExportCode").Value:
            src.FirstOrDefault(k => k.Key == "CountryOriginCode").Value)
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM