Home > front end >  AutoMapper - Assign a value manually depending on the value of the source
AutoMapper - Assign a value manually depending on the value of the source

Time:11-11

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 an int. So if src.Status == 1, my dest.Sent = false, if src.Status == 2, my dest.Sent = true. Is it possible to achieve this?

CodePudding user response:

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

  • Related