What's Automapper for?

0 votes
asked Jan 19, 2010 by quintin-par

What’s Automapper for? How will it help me with my domain and controller layer (asp.net mvc)

3 Answers

0 votes
answered Jan 19, 2010 by jason

If you have an object of one type and you want to populate the properties of an object of another type using properties from the first type, you have two choices:

  1. Manually write code to do such a mapping.
  2. Use a tool that will automatically handle this for you.

AutoMapper is an example of 2.

The most common use is to flatten models into a data transfer objects (or, in general, mapping across layer boundaries). What's very nice about AutoMapper is that for common scenarios you don't have to do any configuring (convention over configuration).

0 votes
answered Jan 19, 2010 by ozczecho

Map objects between layers. Good example: Here

0 votes
answered Jan 19, 2010 by aaronaught

Maybe an example will help here...

Let's say you have a nicely-normalized database schema like this:

Orders       (OrderID, CustomerID, OrderDate)  
Customers    (CustomerID, Name)  
OrderDetails (OrderDetID, OrderID, ProductID, Qty)  
Products     (ProductID, ProductName, UnitPrice)  

And let's say you're using a nice O/R mapper that hands you back a well-organized domain model:


Now you're given a requirement to display everything that's been ordered in the last month. You want to bind this to a flat grid, so you dutifully write a flat class to bind:

public class OrderDetailDto
    public int ID { get; set; }
    public DateTime OrderDate { get; set; }
    public int OrderCustomerID { get; set; }
    public string OrderCustomerName { get; set; }
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public Decimal ProductUnitPrice { get; set; }
    public int Qty { get; set; }

    public Decimal TotalPrice
        get { return ProductUnitPrice * Qty; }

That was pretty painless so far, but what now? How do we turn a bunch of OrderDetails into a bunch of OrderDetailDtos for data binding?

You might put a constructor on OrderDto that takes an OrderDetail, and write a big mess of mapping code. Or you might have a static conversion class somewhere. Or, you could use AutoMapper, and write this instead:

Mapper.CreateMap<OrderDetail, OrderDetailDto>();
OrderDetailDto[] items =
    Mapper.Map<OrderDetail[], OrderDetailDto[]>(orderDetails);
GridView1.DataSource = items;

There. We've just taken what would otherwise have been a disgusting mess of pointless mapping code and reduced it into three lines (really just two for the actual mapping).

Does that help explain the purpose?

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter