簡體   English   中英

使用 Automapper 到 map 從對象列表到單個 object 使用來自源的屬性值

[英]Use Automapper to map from a list of objects to a single object using property values from 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; }
}

目的地:

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

源 PriceDetail 可能類似於:

  • 服務代碼 = "MetalLevel"
  • 服務價值 = “黃金”

我需要 map PriceDetail 到 PlanEntity,例如:

  • 如果 PriceDetail.ServiceCode = "MetalLevel" 然后 map 它到 PlanEntity.MetalLevel
  • 如果 PriceDetail.ServiceCode = "RxCode" 然后 map 它到 PlanEntity.RxCode
  • ETC..

我知道映射器中會有硬編碼邏輯,但不確定如何或是否可以使用 automapper。 非常感謝任何提示或建議。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM