首页 文章

automapper根据枚举值映射某些bool属性

提问于
浏览
2

目标类有一个bool列表 . 映射到目标类的DTO具有1个枚举属性 . 取决于枚举是什么,应该设置目标类中的一些bool . 如何在automapper中实现它? .ForMember()将无法工作,因为我必须对每个bool属性进行枚举逻辑检查 . 我想做一个映射 this.CreateMap<DestinationDTO, Destination>() ,取决于支付是什么Property1或Property2或Property3设置 .

见下文:

public class Destination
{
  public bool? Property1{get; set;}
  public bool? Property2{get; set;}
  public bool? Property3{get;set;}
}

public class DestinationDTO
{
   public Enum Payout{get; set;}
}
public Enum Payout
{
  Proration = 1,
  Recurrent = 2,
  Lumpsum = 3
}

如果DestinationDTO.Payout == Payout.Proration,我想将Destination实体类的Property1设置为true,同样取决于支付的内容,我可能想在实体类中设置另一个Property . 在将DestinationDTO映射到Destination实体类时,我可以在automapper中执行此操作吗?

1 回答

  • 2

    您可以使用 ForMember 表达式执行此操作:

    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<DestinationDTO, Destination>()
            .ForMember(d => d.Property1,
                m => m.MapFrom(d => d.Payout == Payout.Proration ? true : default(bool?)))
            .ForMember(d => d.Property2,
                m => m.MapFrom(d => d.Payout == Payout.Recurrent ? true : default(bool?)))
            .ForMember(d => d.Property3,
                m => m.MapFrom(d => d.Payout == Payout.Lumpsum ? true : default(bool?)));
    });
    
    var mapper = config.CreateMapper();
    
    var dtos = new[]
    {
        new DestinationDTO { Payout = Payout.Proration },
        new DestinationDTO { Payout = Payout.Recurrent },
        new DestinationDTO { Payout = Payout.Lumpsum },
    };
    
    var destinations = dtos.Select(d => mapper.Map<Destination>(d));
    

    偏离主题:我更喜欢不可空的布尔值 . 然后你可以删除 ? true : default(bool?) 部分, Destination 仍然在其所有属性中说出真相 .

相关问题