obautista
obautista

Reputation: 3773

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:

I need to map PriceDetail to PlanEntity such:

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.

Upvotes: 0

Views: 121

Answers (1)

Hesam Akbari
Hesam Akbari

Reputation: 1141

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

Upvotes: 1

Related Questions