Click here to Skip to main content
15,887,821 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I want to map list of Dto to other object to using Automapper

Source:
public class Order
    {
        public List<ShipOnly> Ship { get; set; }
    }
public class ShipOnly
    {
        public string Name { get; set; }   
    }

Destination
public class Order
    {
        public List<ShipOnly> Ship { get; set; }
    }
public class ShipOnly
    {
        public string Name { get; set; }   
    }


What I have tried:

I am stuck here from 2 days.Please help me how to map list with

Mapper.CreateMap<AbcDto, Abcd>()
                .ForMember();


Thanks in advance.
Posted
Updated 21-Sep-17 9:39am

1 solution

You don't need to map the member; you just need to map both types.

Given:
C#
namespace Db
{
    public class Order
    {
        public List<ShipOnly> Ship { get; set; }
    }
    
    public class ShipOnly
    {
        public string Name { get; set; }   
    }
}

namespace Dto
{
    public class Order
    {
        public List<ShipOnly> Ship { get; set; }
    }
    
    public class ShipOnly
    {
        public string Name { get; set; }   
    }
}

Initialization:
C#
Mapper.Initialize(cfg => {
    cfg.CreateMap<Db.Order, Dto.Order>();
    cfg.CreateMap<Db.ShipOnly, Dto.ShipOnly>();
});

Use:
C#
Db.Order source = new Db.Order
{
    Ship = new List<Db.ShipOnly>
    {
        new Db.ShipOnly { Name = "Test" }
    }
};

Dto.Order result = Mapper.Map<Dto.Order>(source);
Debug.Assert(result.Ship != null);
Debug.Assert(result.Ship.Count == 1);
Debug.Assert(result.Ship[0].Name == "Test");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900