Map one object to one of three objects

Viewed 81

Please see the code below, which I took from here: https://github.com/AutoMapper/AutoMapper/wiki/Mapping-inheritance (Runtime Polymorphism section)

    public class Order { }
        public class OnlineOrder : Order { }
        public class MailOrder : Order { }

        public class OrderDto { }
        public class OnlineOrderDto : OrderDto { }
        public class MailOrderDto : OrderDto { }

        Mapper.Initialize(cfg => {
        cfg.CreateMap<Order, OrderDto>()
              .Include<OnlineOrder, OnlineOrderDto>()
              .Include<MailOrder, MailOrderDto>();
        cfg.CreateMap<OnlineOrder, OnlineOrderDto>();
        cfg.CreateMap<MailOrder, MailOrderDto>();
        });

        // Perform Mapping
        var order = new OnlineOrder();
        var mapped = Mapper.Map(order, order.GetType(), typeof(OrderDto));
        Assert.IsType<OnlineOrderDto>(mapped);

It works as expected. Say I changed the code to as follows:

https://github.com/AutoMapper/AutoMapper/wiki/Mapping-inheritance

public class Order { 
        public class OnlineOrder : Order { int type;}}

        public class OrderDto { }
        public class OnlineOrderDto : OrderDto { }
        public class MailOrderDto : OrderDto { }

Say I wanted to map OnlineOrder to one of the DTOs following this logic:

if (OnlineOrder.Type==1) { return new OnlineOrderDto() }
elseif (OnlineOrder.Type==2) { return new MailOrderDto() }

I am actually trying to do this in LINQ to Entities:

list = CreditCardPreQualificationDatabase
                        .dbOffers
                        .Select(Mapper.Map<OrderDTO>)
                        .ToList();

After this has run; list should contain types of: OnlineOrderDto and MailOrderDto

Is it possible to do this?

0 Answers
Related