dimanche 14 février 2016

Automapper - Map custom object nested inside List of object

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.





Aucun commentaire:

Enregistrer un commentaire