c# - 自动映射器根据枚举值映射某些 bool 属性

标签 c# automapper

目标类有一个 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 中执行此操作吗?

最佳答案

您可以使用 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));

题外话:我更喜欢不可为空的 bool 值。那么你可以删除吗? true :default(bool?) 部分和 Destination 的所有属性仍然说明事实。

关于c# - 自动映射器根据枚举值映射某些 bool 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107588/

相关文章:

c# - 如何使用 AutoMapper 将数字数组映射到映射表内的属性

asp.net - 如何使用 AutoMapper 将多个对象映射到一个对象 - asp.net mvc 3

Automapper:对相同类型使用类型转换器和值解析器

c# - 无法将字符串转换为 TimeSpan

c# - 在 C# 中根据引用的 XSD 验证 XML

c# - 重写 api 和反序列化对象

c# - 从扩展方法中消除可推断的泛型类型参数

c# - 如何处理单击按钮时使用 Javascript 弹出的 Yes No 对话框

c# - 正则表达式匹配除字符列表以外的所有内容

c# - struct 的 const 数组的初始化