Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to using AutoMapper to map a child list object

Tags:

c#

automapper

I have 2 objects : Parent and ParentDTO :

    public class Parent
    {
        public int ParentID { get; set;}
        public string ParentCode { get; set; }
        public List<Child> ListChild { get; set; }
    }

    public class Child
    {
        public int ChildID { get; set; }
        public string ChildCode { get; set; }
    }

    public class ParentDTO
    {
        public int ParentID { get; set; }
        public string ParentCode { get; set; }
        public List<ChildDTO> ListChild { get; set; }
    }

    public class ChildDTO
    {
        public int ChildID { get; set; }
        public string ChildCode { get; set; }
    }

I want to using AutoMapper to map data from Parent object to ParentDTO object (all data in ListChild has to transfer to ListChildDTO)

Can anyone help me. Thanks

like image 792
quangho Avatar asked Feb 15 '23 07:02

quangho


1 Answers

You should be able to just create the top level mappings, and AutoMapper will automatically map the list.

//Create Mappings
Mapper.CreateMap<Parent, ParentDto>();
Mapper.CreateMap<Child, ChildDto>();

//Map
Mapper.Map<Parent, ParentDto>();

Check out the Wiki on the AutoMapper project site on GitHub. http://docs.automapper.org/en/stable/Lists-and-arrays.html

like image 86
GetFuzzy Avatar answered Feb 23 '23 12:02

GetFuzzy