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?
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
Aftermapmethod. It gives you more freedom to add some extra complexity. In this case you could create a Map like this:You ignore the properties you want to map in the
Aftermapmethod. In your case theAftermapwould look something like this: