Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading