简体   繁体   中英

Use Automapper to map from a list of objects to a single object using property values from source

Source:

public class Message 
{
    public DateTime AcceptedDate { get; set; }
    public List<PriceDetail> PriceDetails { get; set; }
}

public class PriceDetail 
{
    public string ServiceCode { get; set; }
    public string ServiceValue { get; set; }
}

Destination:

public class GroupEntity 
{
    public DateTime AcceptedDate { get; set; }
    public List<PlanEntity> Plans { get; set; }
}

public class PlanEntity 
{
    public string MetalLevel { get; set; }
    public string MdCode { get; set; }
    public string RxCode { get; set; }
    public string PercentChange { get; set; }
}

Source PriceDetail could be something like:

  • ServiceCode = "MetalLevel"
  • ServiceValue = "Gold"

I need to map PriceDetail to PlanEntity such:

  • if PriceDetail.ServiceCode = "MetalLevel" then map it to PlanEntity.MetalLevel
  • if PriceDetail.ServiceCode = "RxCode" then map it to PlanEntity.RxCode
  • etc..

I understand there will be hard coded logic in the mapper, but not sure how or if this is possible using automapper. Any tips or suggestion are very much appreciated.

CreateMap<PriceDetail, PlanEntity>()
           .ForMember(dest => dest.MetalLevel, opt => {
               opt.PreCondition(src => src.ServiceCode=="MetalLevel");
               opt.MapFrom(src => src.ServiceCode);
           });
CreateMap<PriceDetail, PlanEntity>()
           .ForMember(dest => dest.RxCode, opt => {
               opt.PreCondition(src => src.ServiceCode=="RxCode");
               opt.MapFrom(src => src.ServiceCode);
           });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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