Assigning a value manually in Automapper depending on the value of the source

Advertisements

I would like to assign a value manually to a DTO property in the Profile of the Automapper depending on the value I have in my entity.

Below you can see my code, but it doesn’t work as expected because the .AfterMap is independent from the .Condition, as a matter of fact every dest.Sent is mapped with true:

.ForMember(
    dest => dest.Sent,
    opts => opts.Condition(src => src.Status == 2 && src.Status != 1)
)
.AfterMap((notification, dto) =>
    dto.Sent = true);

My DTO

public class NotificationItemDTO
{
    public long Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Type { get; set; }
    public bool Sent { get; set; }
}

My Source

public class Notification
{
    public long Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Type { get; set; }
    public int Status { get; set; }
}

I wish to assign a value to dest.Sent which is a bool depending on src.Status which is a int. So if src.Status == 1 my dest.Sent = false, if src.Status == 2 my dest.Sent = true. Is it possible to achieve this?

>Solution :

You have misunderstood the usage of .Condition().

AutoMapper allows you to add conditions to properties that must be met before that property will be mapped.

Hence, from your scenario, you are trying to assign a different value to the destination based on condition but not block the mapping from source to destination by condition which is the main purpose of .Condition().

While .AfterMap() is the last action to be executed after the mapping definition logic is executed, hence the value will be overridden.


Using .MapFrom() and defining the logic to set the destination’s Sent is true only when the source’s Status is 2.

CreateMap<Notification, NotificationItemDTO>()
    .ForMember(
        dest => dest.Sent,
        opts => opts.MapFrom(src => src.Status == 2)
    ); 

Demo @ .NET Fiddle

Leave a ReplyCancel reply