Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
863 views
in Technique[技术] by (71.8m points)

c# - AutoMapper flatten nested collections

I try to figure out how to flatten a collection of Merchants, each containing a collection of Orders to a flat List of OrderViewModels.

Here my DTO:

public class Merchant
{
    public string MerchantName { get; set; }
    public List<Order> Orders { get; set; }
}

public class Order
{
    public string OrderId { get; set; }
}

And Here's the view model:

public class OrderViewModel
{
    public string MerchantName { get; set; }
    public string OrderId { get; set; }
}

My Goal is to flatten a List<Merchant> to a List<OrderViewModel> whereas the following test structure should result in 6 view models:

var myMerchants = new List<Merchant>
{
    new Merchant
    {
        MerchantName = "Merchant X",
        Orders = new List<Order>
        {
             new Order { OrderId = "Order 1"},
             new Order { OrderId = "Order 2"},
             new Order { OrderId = "Order 3"}
        }
    },
    new Merchant
    {
        MerchantName = "Merchant Y",
        Orders = new List<Order>
        {
            new Order { OrderId = "Order 4"},
            new Order { OrderId = "Order 5"},
            new Order { OrderId = "Order 6"}
        }
    }
 };

 var models = Mapper.Map<List<OrderViewModel>>(myMerchants);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because the cardinality of the root objects isn't 1:1, (i.e. 2 root Merchants need to map to 6 OrderViewModels), you may need to resort to a custom TypeConverter and operate at the collection level, where you can use .SelectMany to do the flattening:

public class MyTypeConverter : ITypeConverter<IEnumerable<Merchant>, List<OrderViewModel>>
{
    public List<OrderViewModel> Convert(ResolutionContext context)
    {
        if (context == null || context.IsSourceValueNull)
            return null;

        var source = context.SourceValue as IEnumerable<Merchant>;

        return source
            .SelectMany(s => s.Orders
              .Select(o => new OrderViewModel
              {
                  MerchantName = s.MerchantName,
                  OrderId = o.OrderId
              }))
              .ToList();
    }
}

Which you can then bootstrap:

Mapper.CreateMap<IEnumerable<Merchant>, List<OrderViewModel>>()
    .ConvertUsing<MyTypeConverter>();

And then mapped as such:

var models = Mapper.Map<List<OrderViewModel>>(myMerchants);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...