Map IList to ICollection through AutoMapper

邮差的信 提交于 2019-12-19 05:06:45

问题


public class Order
{
    public int OrderId { get; set; }
    public string OrderCode { get; set; }
    public IList<OrderItem> OrderItems { get; set; }
}

public class OrderDTO
{
    public string OrderId { get; set; }
    public string IdentifiableCode { get; set; }
    public decimal TotalCost { get; set; }
    public ICollection OrderItems { get; set; }
}

public class OrderItem
{
    public int OrderItemId { get; set; }
    public int ItemCount { get; set; }
    public Order Order { get; set; }
}

public class OrderItemDTO
{
    public int OrderItemId { get; set; }
    public int ItemCount { get; set; }
    public OrderDTO Order { get; set; }
}

In this scenario how can i map IList of OrderItems to ICollection. I tried to use resolver but ended up in recursive since OrderItem has Order reference.

Any ideas?


回答1:


First off, I added a few tweaks to your classes. One was to add constructors that initialize the collections so I could add to them in my test. Second, I don't see why you'd want the OrderDTO.OrderItems to be a loosely-typed ICollection. If you do that, Automapper just assigns the IList to the ICollection (since IList implements ICollection). If you define it as IList, Automapper will see that it knows how to convert from OrderItem to OrderItemDTO and will map each member of the collection.

I also had to add some Ignore()'s since OrderItemDTO doesn't contain IdentifiableCode nor TotalCost (not sure what you wanted to do with those). Finally, the parent/child mapping (OrderItemDTO having a reference to its parent) can be done by a simple foreach loop in the AfterMap(). So here's the mapping I came up with:

Mapper.CreateMap<Order, OrderDTO>()
    .ForMember(d => d.IdentifiableCode, o => o.Ignore())
    .ForMember(d => d.TotalCost, o => o.Ignore())
    .AfterMap((s, d) =>
                {
                    foreach (var l in d.OrderItems)
                    {
                        l.Order = d;
                    }
                });
Mapper.CreateMap<OrderItem, OrderItemDTO>();
Mapper.AssertConfigurationIsValid();

And here's the test I used to check things out:

var order = new Order
                {
                    OrderCode = "AAA",
                    OrderId = 22,
                    OrderItems = new List<OrderItem>(),
                };
order.OrderItems.Add(new OrderItem { ItemCount = 2, Order = order, OrderItemId = 33 });
order.OrderItems.Add(new OrderItem { ItemCount = 1, Order = order, OrderItemId = 99 });

var mapped = Mapper.Map<Order, OrderDTO>(order);


来源:https://stackoverflow.com/questions/5483174/map-ilist-to-icollection-through-automapper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!