Jason Jay
Jason Jay

Reputation: 175

AutoMapper Conditional Mapping

If ready to start is false, then I need to set ActualStartDate to default. Or maybe I will make a nullable instead.

The RequestDates collection will always have just 1 record.

    public class EngagementDto
    {
        #region Public Properties

        public bool ReadyToStart { get; set; }

        public IEnumerable<RequestDateDto> RequestDates { get; set; }

        #endregion
    }

    public class RequestDateDto
    {
        #region Public Properties

        public DateTime ActualStartDate { get; set; }

        #endregion
    }   

Not sure If I'm going about this correctly...but this is what I have so far.

            CreateMap<EngagementDto, RequestDateDto>()
                .ForMember(dest => dest.ActualStartDate, opt =>
                {
                    opt.Condition((src, dest) => !src.ReadyToStart);
                    opt.MapFrom(dest => dest.);
                }

Upvotes: 0

Views: 942

Answers (1)

evilGenius
evilGenius

Reputation: 1101

Try this, i think it's can be working!

 CreateMap<EngagementDto, RequestDateDto>()
                ForMember(dest => dest.RequestDates, 
                   opt => opt.MapFrom
                   (src => dest.ReadyToStart ? "your default value" : src.ActualStartDate));

way number two

change your model like this

public IEnumerable<RequestDateDto> RequestDates { get; set; } = null

and then

CreateMap<EngagementDto,RequestDateDto>()
    .ForMember(dest => dest.RequestDates, opt => {
        opt.PreCondition(src => (src.ReadyToStart));
        opt.MapFrom(src => src.ActualStartDate);

Upvotes: 2

Related Questions