简体   繁体   中英

Mapping properties that are collection types

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.

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>();                                 
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM