繁体   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