Automapper - Map custom object nested inside List of object

2.5k Views Asked by At

I need to map List<Source> to List<Dest>, The issue is that Source contains NestedObject inside it & Dest also contains a NestedObject inside it. I need to map these two also while my List is being mapped. I have tried everything but either the nested object always remains null and doesnt get mapped or I get the following exception:

Missing type map configuration or unsupported mapping. Mapping types: .....

Structure of Source & Destinations:

Source:

 public class Source {
        public string Prop1 { get; set; }
        public CustomObjectSource NestedProp{ get; set; }
        }
  public class CustomObjectSource {
        public string Key { get; set; }
        public string Value{ get; set; }
        }

Destination:

 public class Destination {
        public string Prop1 { get; set; }
        public CustomObjectDest NestedProp{ get; set; }
        }
  public class CustomObjectDest {
        public string Key { get; set; }
        public string Value{ get; set; }
        }

What I have tried: I have the following code, tried several other approaches also but to no avail:

var config = new MapperConfiguration(c =>
                {
                    c.CreateMap<Source, Destination>()
                      .AfterMap((Src, Dest) => Dest.NestedProp = new Dest.NestedProp
                      {
                          Key = Src.NestedProp.Key,
                          Value = Src.NestedProp.Value
                      });
                });                
                var mapper = config.CreateMapper();

var destinations = mapper.Map<List<Source>, List<Destination>>(MySourceList.ToList());

I am stuck with this for days, Kindly help.

1

There are 1 best solutions below

2
On BEST ANSWER

You got to map the CustomObjectSource to CustomObjectDest as well.

This should do it:

var config = new MapperConfiguration(c =>
        {
            c.CreateMap<CustomObjectSource, CustomObjectDest>();
            c.CreateMap<Source, Destination>()
              .AfterMap((Src, Dest) => Dest.NestedProp = new CustomObjectDest
              {
                  Key = Src.NestedProp.Key,
                  Value = Src.NestedProp.Value
              });
        });
        var mapper = config.CreateMapper();

        var MySourceList = new List<Source>
        {
            new Source
            {
                Prop1 = "prop1",
                NestedProp = new CustomObjectSource()
                {
                    Key = "key",
                    Value = "val"
                }
            }
        };

        var destinations = mapper.Map<List<Source>, List<Destination>>(MySourceList.ToList());