开发者

Map IList to ICollection through AutoMapper

开发者 https://www.devze.com 2023-02-20 13:12 出处:网络
public class Order { public int OrderId { get; set; } public string OrderCode { get; set; } public IList<OrderItem> OrderItems { get; set; }
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; }
    publi开发者_运维知识库c 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?


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号