Automapper Unflatten to List

Viewed 463

I have flat tabular data that I need to turn into hierarchical data, and I'm trying to do this with AutoMapper. Here is a sketch of the tabular DTO source and the master/detail destination classes.

public class FlatDTO
{
    public string Supplier { get; set; }
    public string OrderNumber { get; set; }
    public string ItemNumber { get; set; }
    public string Amount { get; set; }
}

and the destination objects look like this:

public class Order
{
    public string AccountName { get; set; }
    public string OrderNumber { get; set; }
    List<OrderLines> OrderLines { get; set; }
}

public class OrderLines 
{
    public string Item { get; set; }
    public string Amount { get; set; }
}

My Automapper profile looks like this:

public class MyAutomapperProfile : Profile
{
    public MyAutomaperProfile ()
    {
        CreateMap<FlatDto, Order>()
          .ForMember(des => des.Account, opt => opt.MapFrom(src => src.Supplier))
          .ReverseMap();

        CreateMap<FlatDto, OrderLines>()
          .ForMember(des => des.Item, opt => opt.MapFrom(src => src.Item))
          .ReverseMap();
    }
}

The function performing the Transform:

public Order Transform (List<FlatDto> data)
{
     var output = injectedFromCtorIMapper.Map<Order>(data);
     //throws AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping 
}

Example Source Data:

Customer1    1234    Item1   200
Customer1    1234    Item2   500
Customer1    1234    Item3   4000

Target should look like (not actually Json but looks better):

Order
{ 
    AccountName = "Customer 1",
    OrderNumber = "1234",
    OrderLines [
                   OrderLine
                   {
                      Item: "Item1",
                      Amount: 200
                   },
                   OrderLine
                   {
                      Item: "Item2",
                      Amount: 500
                   }
                   OrderLine,
                   {
                      Item: "Item3",
                      Amount: 4000
                   }
                ]
}

A few Questions:

  1. Is this possible with Automapper, and what should the mapping profile look like to support this scenario?

  2. How would Automapper handle if row 2 had a value of 'Customer 2'? Overwrite the first value i.e. last one in wins?

2 Answers

To complete the edit of Stefan; here's an example of how you can do it if you need to have a multiple group by. Understanding your expected result in your question, you want to group the master/detail data on AcccountName and OrderNumber. This can be achieved by, indeed, mapping the IEnumerable and by using the Automapper's "ProjectTo" extension (from namespace AutoMapper.QueryableExtensions). In my sample data I added one row with a different OrderNumber to illustrate this.

using AutoMapper;
using AutoMapper.QueryableExtensions;
using System.Collections.Generic;
using System.Linq;

namespace AutomapperUnflatten
{
    public class FlatDTO
    {
        public string Supplier { get; set; }
        public string OrderNumber { get; set; }
        public string ItemNumber { get; set; }
        public string Amount { get; set; }
    }

    public class Order
    {
        public string AccountName { get; set; }
        public string OrderNumber { get; set; }
        public List<OrderLines> OrderLines { get; set; }
    }

    public class OrderLines
    {
        public string Item { get; set; }
        public string Amount { get; set; }
    }


    class Program
    {
        static void Main(string[] args)
        {            
            var configuration = new MapperConfiguration(cfg => {
                cfg.CreateMap<IEnumerable<FlatDTO>, Order>()
                     .ForMember(d => d.AccountName, opt => opt.MapFrom(src => src.FirstOrDefault().Supplier))
                     .ForMember(d => d.OrderNumber, opt => opt.MapFrom(src => src.FirstOrDefault().OrderNumber))
                     .ForMember(d => d.OrderLines, opt => opt.MapFrom(src =>
                         src.Select(s => new OrderLines() { Item = s.ItemNumber, Amount = s.Amount })));
                     });


            var inputData = new List<FlatDTO>()
            {
                new FlatDTO(){ Supplier = "Customer1", OrderNumber = "1234", ItemNumber = "Item1", Amount = "200"},
                new FlatDTO(){ Supplier = "Customer1", OrderNumber = "1234", ItemNumber = "Item1", Amount = "500"},
                new FlatDTO(){ Supplier = "Customer1", OrderNumber = "1234", ItemNumber = "Item1", Amount = "4000"},
                new FlatDTO(){ Supplier = "Customer1", OrderNumber = "9999", ItemNumber = "Item1", Amount = "4000"},
            };
            

            var result = inputData.GroupBy(c => (c.Supplier, c.OrderNumber)).Select(f => f).AsQueryable().ProjectTo<Order>(configuration);            
        }
    }
}

Is this possible with Automapper, and what should the mapping profile look like to support this scenario?

Yes, this is possible - but do note: also AutoMapper has it's limitations. Not all transformations are suited to be handled with AutoMapper.

Do note: List<OrderLines> OrderLines { get; set; } must be public

I don't have all the details yes, but basically you can create a map from IEnumerable<FlatDTO> to Order. I will work out an example.

Example

CreateMap<IEnumerable<FlatDTO>, Order>()
   .ForMember(d => d.AccountName, o => o.MapFrom(s=> s.Select(c => c.Supplier).FirstOrDefault()))
   .ForMember(d => d.OrderLines, o => o.MapFrom(s=> s.Select(c => new OrderLines()
       {
           Amount = c.Amount,
           Item = c.ItemNumber,
       })));

How would Automapper handle if row 2 had a value of 'Customer 2'? Overwrite the first value i.e. last one in wins?

Depending on your mapping logic, it depends. You can even perform a check on these doubles by using the AfterMap or BeforeMap methods - doesn't make it faster though.

Ideally, you initial set can be mapped to a single order, thus, containing a single customer. - Otherwise, you'll need a mapping from IEnumerable<FlatDTO> to IEnumerable<Order> - which is really pushing the limits.


Tester

static void Main(string[] args)
{
    var dtos = new[]
    {
       new FlatDTO() {Supplier = "you", Amount = "10", ItemNumber = "1", OrderNumber = "123"},
       new FlatDTO() {Supplier = "you", Amount = "12", ItemNumber = "2", OrderNumber = "234"}
    };

    var config = new MapperConfiguration(cfg => cfg.AddProfile<MyAutomapperProfile>());
    var mapper = config.CreateMapper();

    var order = mapper.Map<IEnumerable<FlatDTO>, Order>(dtos);
}
Related