目标类有一个 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/