Reputation: 943
The destination class has a list of bools. The DTO that gets mapped to the destination class has 1 enum property. depending on what the enum is some of the bools in the destination class should be set. how to achieve it in automapper?
.ForMember() won't work because i would have to do enum logic check for each of the bool property.
I want to do a mapping this.CreateMap<DestinationDTO, Destination>()
where depending on what the payout is Property1 or Property2 or Property3 gets set.
See below:
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
}
If the DestinationDTO.Payout == Payout.Proration, I want to set Destination entity class's Property1 to be true, similarly depending on what payout it is, I might want to set another Property in the entity class. Can I do this in automapper when mapping the DestinationDTO to Destination entity class?
Upvotes: 2
Views: 2798
Reputation: 109185
You can do this by using ForMember
expressions:
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));
Off-topic: I'd prefer non-nullable booleans. Then you can remove the ? true : default(bool?)
parts and a Destination
still tells the truth in all of its properties.
Upvotes: 2