Search code examples
c#automappermapper

place condition on the input value via aftermap in the mapper profile


I send a value through Aftermap to profile mapper.

var provinces = await _repository.AsQueryable().ToListAsync();
var result = provinces.Select(item => _mapper.Map<GetProvincesDto>(item, x => x.AfterMap((src, dst) => dst.Language = "en"))).ToList();

Now, based on the value sent inside the profile, I want to Condition that if the value of the input language is English, I will map English names, and otherwise, I will map another value.

public class ProvinceToGetProvincesDto : Profile
{
    public ProvinceToGetProvincesDto()
    {
        CreateMap<Province, GetProvincesDto>()
            .ForMember(x => x.Id, x => x.MapFrom(x => x.Id))
            .ForMember(x => x.Name, x => x.MapFrom (x => x.language == "en" ? x.EnglishName.Value : x.Name.Value));
    }
}

Solution

  • I doubt that there is not possible to pass the value outside of the mapping profile to perform the mapping.

    What you do with the .AfterMap() is correct direction, just need to modify your mapping profile (rule) and AfterMap action.

    public class ProvinceToGetProvincesDto : Profile
    {
        public ProvinceToGetProvincesDto()
        {
            CreateMap<Province, GetProvincesDto>()
                .ForMember(x => x.Id, x => x.MapFrom(x => x.Id))
                .ForMember(x => x.Name, x => x.MapFrom(x => x.Name.Value));
        }
    }
    
    var result = provinces.Select(item => _mapper.Map<Province, GetProvincesDto>(item, opt =>
        {
            opt.AfterMap((src, dest) => dest.Name = lang == "en" ? src.EnglishName.Value : src.Name.Value);
        })
    ).ToList();
    

    Reference: Before and After Map Action