How can I map a flat objects list with children fields in a single object, grouping by a field (like source Id field) using AutoMapper with C#?
I've tried use ITypeConverter from AutoMapper documentation, but still not worked.
public class FlatSource
   {
       public int Id { get; set; }
       public string Name { get; set; }
 
       public int FirstChildId { get; set; }
       public string FirstChildName { get; set; }
 
       public int SecondChildId { get; set; }
 
       public string SecondChildName { get; set; }        
   }
 
 
   public class Destination {
       
       public int Id { get; set; }
       public string Name { get; set; }
       public List<FirstChild> Childrens { get; set; }
       public SecondChild SecondChild { get; set; }
   }
 
   public class FirstChild {
       
       public int Id { get; set; }
       public string Name { get; set; }
   }
 
   public class SecondChild {
       
       public int Id { get; set; }
       public string Name { get; set; }
   }
Consider a List of FlatSource objects:
FlatSourceArray:[
{Id: 1, Name: "Bob", FirstChildId: 1, FiirstChildName: "John", SecondChildId: 10, SecondChildName: "Pilot" },
{Id: 1, Name: "Bob", FirstChildId: 2, FiirstChildName: "Maxi", SecondChildId: 10, SecondChildName: "Pilot" }, 
{Id: 1, Name: "Bob", FirstChildId: 3, FiirstChildName: "Mary", SecondChildId: 10, SecondChildName: "Pilot" }
]
So, I expect convert to a single object like:
Destination:{
  Id: 1,
  Name:"Bob",
  Childrens": [
  {Id:1, Name: "John"},
  {Id:2, Name: "Max"},
  {Id:3, Name: "Mary"}
 ],
 SecondChild: {Id:10, Name: "Pilot"}
}
Use ReverseMap() and then specify the custom mapping from first child to children list.
Read more about unflattening in documentation.
CreateMap<Destination, FlatSource>()
    .ReverseMap()
    .ForPath(d => d.Childrens, o => o.MapFrom(s => new List<FirstChild>
    {
        new FirstChild
        {
            Id = s.FirstChildId,
            Name = s.FirstChildName,
        },
    }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With