Search code examples
c#.netautomapperautomapper-6

Automapper flattened DTO to Parent with Child Collection


I have a flattened DTO which I need to map to a Parent with Children relationship. I'd like to do this via AutoMapper as I'm using it in other places and it works great. I've seen examples of mapping a Parent and Child but not when the Child is a collection and the source is a flattened DTO. I've created some classes that I can use for getting the configuration correct. Below are my sample classes:

public class Parent
{
    public int ParentId { get; set; }
    public string ParentName { get; set; }

    public List<Child> Children { get; set; }
}
public class Child
{
    public int ChildId { get; set; }
    public string ChildName { get; set; }
}
public class ParentChildDTO
{
    public int ParentId { get; set; }
    public string ParentName { get; set; }
    public int ChildId { get; set; }
    public string ChildName { get; set; }
}

I'm performing the mapper initialization on startup. I'm not getting any errors until I try to perform the mapping. Below is my mapper initialization code. I've kept in the commented out line to show the other way that I've tried to accomplish this:

AutoMapper.Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<ParentChildDTO, Child>();
                cfg.CreateMap<ParentChildDTO, Parent>()
                    .ForMember(dest => dest.Children, opt => opt.MapFrom(src => src));
                    //.ForMember(dest => dest.Children, opt => opt.MapFrom(src => new Child { ChildId = src.ChildId, ChildName = src.ChildName }));               

            });

Below is my code that I'm using for trying to perform the mapping configuration:

ParentChildDTO parentChildDTO = new ParentChildDTO { ParentId = 1, ParentName = "Parent Name", ChildId = 2, ChildName = "Child Name" };
Parent parent = AutoMapper.Mapper.Map<ParentChildDTO, Parent>(parentChildDTO);

List<LienActivity> mapTest = AutoMapper.Mapper.Map<List<BaseActivityUploadDTO>, List<LienActivity>>(request.Activities);

I've considered using a Custom Value Resolver, but was hoping to avoid the complexity and extra code if what I'm doing is possible with the correct configuration.

Here's the error that I get with the above code:

Error mapping types.

Mapping types: ParentChildDTO -> Parent

Type Map configuration: ParentChildDTO -> Parent

Property: Children


Solution

  • Here is another option where you define custom mapping just for the Children property.

    Mapper.Initialize(cfg =>
    {
       cfg.CreateMap<ParentChildDTO, Parent>()
          .ForMember(d => d.Children, 
             opt => opt.MapFrom(src => new List<Child>() { new Child() { ChildId = src.ChildId, ChildName = src.ChildName } }));
    });