Automapper flattened DTO to Parent with Child Collection

4,919 views
Skip to first unread message

billy.r...@gmail.com

unread,
Mar 26, 2018, 2:48:42 PM3/26/18
to AutoMapper-users
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.\r\n\r\nMapping types:\r\nParentChildDTO -> Parent\r\nMTAG.Activities.API.ParentChildDTO -> MTAG.Activities.API.Parent\r\n\r\nType Map configuration:\r\nParentChildDTO -> Parent\r\nMTAG.Activities.API.ParentChildDTO -> MTAG.Activities.API.Parent\r\n\r\nProperty:\r\nChildren



Reply all
Reply to author
Forward
0 new messages