Mapping properties that are collection types

51 Views Asked by At

Say I have a classes like this in a business layer:

Namespace Business
{
public class Order
    {
        public int ID { get; set; }
        public List <OrderItem> OrderItems { get; set; }
    }

public class OrderItem
    {
        public int ID { get; set; }
        public int ProductID { get; set; }
    }
}

and classes like this in a Model layer:

Namespace Model
{
public class OrderModel
    {
        public int ID { get; set; }
        public List <OrderItem> OrderItems { get; set; }
    }

public class OrderItemModel
    {
        public int ID { get; set; }
        public int ProductID { get; set; }
    }
}

How would I map the order class in the Business Layer to the Order class in the Model layer? I have tried this:

Mapper.Initialize(cfg => 
                {
                    cfg.CreateMap<Order, OrderModel>();
                    cfg.CreateMap<OrderModel, Order>();
                });

It does not work because of the OrderItem property in the Order class. If I remove the OrderItem property then it works. How do I include the orderitem property in the mapping.

I am using version 6.02 of Automapper.

1

There are 1 best solutions below

2
On BEST ANSWER

There is no reason for the collection to not be mapped automatically since names match. So far I see, you have missed the mapping between OrderItem and OrderItemModel

Mapper.Initialize(cfg => 
            {
                cfg.CreateMap<OrderItem, OrderItemModel>();
                cfg.CreateMap<OrderItemModel, OrderItem>();
                cfg.CreateMap<Order, OrderModel>();
                cfg.CreateMap<OrderModel, Order>();                                 
            });