X

Automapper: Mapping objects Part 1 of 7 (NullSubstitution)

automapper

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

//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();          
            var model = AutoMapper.Mapper.Map, IEnumerable>(customers);
                       
            return View(model);
        }

//View

Customers

@foreach (var customer in Model) {

@("Name : " + customer.Name)
@("Bio : " + customer.Bio)

}

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 (i.e NullSubsitution) it with something else, our code would then look like

 public ActionResult Index()
        {
            var customers = _respository.GetAll();

            AutoMapper.Mapper.CreateMap()
                .ForMember(dest => dest.Bio, opt => opt.NullSubstitute("N/A"));
            var model = AutoMapper.Mapper.Map, IEnumerable>(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.

Categories: .NET Automapper
Taswar Bhatti:

View Comments (0)

Related Post