X

Automapper: Mapping objects Part 3 of 7 (Nested Mapping)

automapper

In this part we learn about Nested Mapping in Automapper and we will use the same OrderDto Object that we had previously but we will let Automapper to map the inner objects.

Once again here is the Domain Objects First

//Order 
public class Order
    {
        public string OrderNo { get; set; }
        public Customer Customer { get; set;  }
        public DateTime PurchaseDate { get; set; }
        public IEnumerable LineItems { get; set; }
        public bool ShipToHomeAddress { get; set; }
        public decimal GetTotal()
        {
            return LineItems == null ? 0 : LineItems.Sum(x => x.GetTotalPrice());
        }
        public Guid InternalId { get; set; }
    }

//OrderItems
public class OrderItems
    {
        public decimal Price { get; set; }
        public string Name { get; set; }
        public int Quantity { get; set; }
        public decimal GetTotalPrice()
        {
            return Price * Quantity;
        }
    }

The Dto (Data Transfer Object) look like


public class OrderDto
    {
        public string CustomerName { get; set; }
        public decimal Total { get; set; }
        public string OrderNumber { get; set; }
        public IEnumerable LineItems { get; set; }
    }

//OrderItemsDto
public class OrderItemsDto
    {
        public string Name { get; set; }
        public int Quantity { get; set; }
        public decimal Price { get; set; }
    }

This time when we map Order to OrderDto we will also provide the mapping of OrderItems to OrderItemsDto.

public ActionResult OrderItems()
        {
            var orders = _respository.GetAll();

            Mapper.CreateMap()
                .ForMember(dest => dest.OrderNumber, opt => opt.MapFrom(src => src.OrderNo));
                
            Mapper.CreateMap();

            var model = Mapper.Map, IEnumerable>(orders);

            return View(model);
        }
//View

@foreach (var item in Model)
{
    
}
 
Order Number Name Total Items
@item.OrderNumber @item.CustomerName $@item.Total @foreach (var child in item.LineItems) { @string.Format("({0}) {1} - ${2}", @child.Quantity, @child.Name, @child.Price)
}

As you can see I have taught automapper about its inner child/object mapping before calling Map, thus it knows about the inner mapping, our result would show like

In the next part I will be showing projection in Automapper.

Previous Post:
Part 1 NullSubsitution
Part 2 Flattening by Convention

Categories: .NET Automapper
Taswar Bhatti:

View Comments (10)

Related Post