Recently I gave a talk on Automapper in Ottawa .Net Community, so I though I would post the main ideas of the presentation here also.

The demo was based on an Order System where there were just 3 tables/classes, “Order”, “Customer” and “OrderItems”

From the diagram we can see that a Customer has a Bio and if we pull out all the customer from a repository and display it, we may have some of them whom are missing the Bio.

Here is the code of how we are mapping our domain objects to a Dto or ViewModel, we are basically just passing the data to the View to render

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//customer dto
public class CustomerDto
    {
        public string Bio { get; set; }
        public string Name { get; set; }
    }
 
//Controller
public ActionResult Index()
        {
            var customers = _respository.GetAll();
 
            AutoMapper.Mapper.CreateMap<Customer, CustomerDto>();          
            var model = AutoMapper.Mapper.Map<IEnumerable<Customer>, IEnumerable<CustomerDto>>(customers);
 
            return View(model);
        }
 
//View
<h2>Customers</h2>
 
@foreach (var customer in Model)
{
    <p>
    @("Name : " + customer.Name) <br /> 
    @("Bio : " + customer.Bio) <br />
    </p> 
}

Now lets say you want to replace the Null Bio with something like “N/A”, some people may go directly to the razor view code and add that but we can do better with automapper, we can tell automapper that when there is a Null just substitute it with something else, our code would then look like

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
 public ActionResult Index()
        {
            var customers = _respository.GetAll();
 
            AutoMapper.Mapper.CreateMap<Customer, CustomerDto>()
                .ForMember(dest => dest.Bio, opt => opt.NullSubstitute("N/A"));
            var model = AutoMapper.Mapper.Map<IEnumerable<Customer>, IEnumerable<CustomerDto>>(customers);
 
            return View(model);
        }

In doing so we will use the same View but now we have “N/A” for “Uncle Leo” bio.

In part2 we will be talking about how to flatten objects by convention.