0

I am mapping below classes using Automapper

public class InfoDto
{
    public List<string> Names { get; set; }
}

public class Info
{
    public List<string> Names { get; set; }
}

I want to preserve destination Names value if source Names is null or empty. I tried configuring Mapper as below, but it seem to be clearing destination Names before mapping.

    CreateMap<InfoDto, Info>()
        .ForMember(d => d.Names,
            opt => opt.MapFrom(
                (src, dest) =>
                    src.Names != null && src.Names.Any() ? src.Names : dest.Names));

var infoDto = new InfoDto{ Names = new List<string>{"Test1", "Test2"}}; 
var info = Mappert.Map<Info>(infoDto);

var infoDto1 = new InfoDto{ Names = null}; 
Mapper.Map<InfoDto, Info>(infoDto1, info); 
// info.Names should be list with 2 values

Is there a way I can retrieve/preserve destination Names value and use it if source Names is empty?

Tushar Kesare
  • 700
  • 8
  • 20
  • When mapping to an existing collection, the destination collection is cleared first. If this is not what you want, take a look at AutoMapper.Collection. – Lucian Bargaoanu Sep 28 '19 at 06:45

1 Answers1

-1

I don't know if there might be another solution but this one I've just tested and works.

I often find it usefull to process the more complex mappings in a Aftermap method. It gives you more freedom to add some extra complexity. In this case you could create a Map like this:

        CreateMap<InfoDto, Info>()
            .ForMember(d => d.Names, opt => opt.Ignore())
            // here you can map other properties just regularly if you want
            .AfterMap(mapNames);

You ignore the properties you want to map in the Aftermap method. In your case the Aftermap would look something like this:

private void mapNames(InfoDto source, Info destination)
    {
        if (source.Names != null && source.Names.Any())
        {
            destination.Names = source.Names;
        }
    }
Stackberg
  • 300
  • 3
  • 12
  • I did try AfterMap before. Problem is destination.Names value is reset and is null in AfterMap(). – Tushar Kesare Sep 27 '19 at 14:24
  • Dit you add the line: `.ForMember(d => d.Names, opt => opt.Ignore())` – Stackberg Sep 27 '19 at 14:28
  • Yes. I am using AutoMapper 8.1.0 – Tushar Kesare Sep 27 '19 at 15:07
  • Then I might not understand your problem correctly. This works perfect when I test. `destination.Names` is being set by the `source.Names` but only when source has an value. Or you sure the mapping is registered and not some sort of default mapping is applied? – Stackberg Sep 27 '19 at 18:31
  • 1
    Yes, `destination.Names` is being set by the `source.Names` when source has an value. But when `source.Names` has no value, I want `destination.Names` to retain its previous value. – Tushar Kesare Sep 27 '19 at 21:00