I want to map my DTO to an entity. The only difference between the two is my dto's use List as collection type and the entities use HashSet. How can I configure Automapper to automatically map to a HashSet when it encounters an ICollection? Currently it just replaces the hashset in the entity with a List.
Example classes and mapping:
cfg.CreateMap<MachineDto, Machine>(MemberList.Source)
cfg.CreateMap<Machine, MachineDto>(MemberList.Destination)
public class Machine
{
public Machine()
{
Segment = new HashSet<Segment>();
}
public long ID { get; set; }
public string Name { get; set; }
public ICollection<Segment> Segment { get; set; }
}
public class Segment
{
public Segment()
{
}
public long ID { get; set; }
public long MachineID { get; set; }
public string Serial { get; set; }
}
public class MachineDto
{
public MachineDto()
{
Segment = new List<SegmentDto>();
}
public long ID { get; set; }
public string Name { get; set; }
public ICollection<SegmentDto> Segment { get; set; }
}
public class SegmentDto
{
public SegmentDto()
{
}
public long ID { get; set; }
public string Serial { get; set; }
}
After a lot of fiddling around with the AfterMap() I found the UseDestinationValue option, when defined it will reuse the existing HashSet instead of replacing the ICollection with a List.
cfg.CreateMap<MachineDto, Machine>(MemberList.Source)
.ForMember(dest => dest.Segment, opt => opt.UseDestinationValue());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.