Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Using AutoMapper in Your ASP.

Net MVC Applications


Posted by Arun Karthick on November 25th, 2013

In this article I will explain the AutoMapper component and how to use it in an Asp.Net MVC application with few
source code samples.

About AutoMapper
AutoMapper is an external component that helps in creating a mapping between a source and destination model
types. Once the mapping is created then the source model object can be converted to a destination model object with
ease and with less cluttered code. The developers can get rid of the explicit conversions as implemented in the
following code.

1. public Car ConvertAutomobileToCar(Automobile automobile)


2. {
3. return new Car()
4. {
5. RegistrationNumber = automobile.RegistrationNumber,
6. Color = automobile.Color,
7. Model = automobile.Model
8. };
9. }
If the classes in the above example have numerous properties and if there are many more such object mapping
needed to be done then it becomes a tedious job for the developer as well as making the code sloppy and prone to
coding errors.

Hands On: Building Your Own Watson Powered Application on Bluemix


Download Now

AutoMapper works on a convention based mechanism, which means that the conventions specified by the
AutoMapper component need to be followed to get it working. The component can be imported to the application
through NuGet packages and more information can be found at AutoMapper.org.
Fig 1.0 shows the AutoMapper components added in the project references after the NuGet package import was
done.

Fig 1.0 - AutoMapper components


AutoMapper in Asp.Net MVC Applications
In Asp.Net MVC applications, strictly a View can be bound to only one Model, the View requires bit more massaged
data than the domain model object and also the properties required for the Views don't exactly match with the domain
models. Due to these facts in Asp.Net MVC, the domain (or business) models need to be converted to the View
models before sending them across to the Views. This is where the AutoMapper component gets its place in Asp.Net
MVC applications, as the object conversion will be required for almost all of the Views.

The conversion using the AutoMapper works in two steps:

1. Create a mapping between the Source and Destination model types. This should be done at the application level
and the best place would be the Global.asax page.

2. Call the Map method wherever the conversion is required.

Mapping Features and Code Samples


In this section I will take you through a few important features that the AutoMapper component exhibits, along with
samples in an Asp.Net MVC application. As a first step create an empty Asp.Net MVC 4 application and name it
LearnAutoMapper. Then add the following models to the MVC application, where Automobile is the domain model
and Car is the View model.

1. public class AutomobileDM


2. {
3. public string AutoMobileType { get; set; }
4. public string RegistrationNumber { get; set; }
5. public string Color { get; set; }
6. public string Model { get; set; }
7. public double Price { get; set; }
8. public double Tax { get; set; }
9. }
10. public class CarVM
11. {
12. public string RegistrationNumber { get; set; }
13. public string Color { get; set; }
14. public string Model { get; set; }
15. }
Add the CarController with the Default index action method. Now add the View named GetCar strongly typed to the
CarVM model and also add the corresponding ActionMethod GetCar. The GetCar method accepts a POST request
from Index view with registrationNumber as the parameter and returns back the GetCar view displaying the details of
the Car.

Flattening
This is a straight one to one mapping between the objects and the mapping is made through the property names.
AutoMapper expects the property names to be the same between the ViewModel and DomainModel.
In the GetCar action method let us use AutoMapper to convert the AutomobileDM to CarDM. The source code
example is provided below.

1. [HttpPost]
2. public ActionResult GetCar(string registrationNumber)
3. {
4. AutomobileDM automobile =
DataAccess.GetAutomobileFromDatabase(registrationNumber);
5.
6. //Create the mapping between AutomobileDM to CarVM
7. Mapper.CreateMap<AutomobileDM, CarVM>();
8.
9. //Perform the conversion and fetch the destination view model
10. CarVM car = Mapper.Map<CarVM>(automobile);
11.
12. return View("GetCar", car);
13. }

Projection Feature
Projection is the feature where you want to create custom mapping between the properties where the property name
doesn’t match or it is not a one to one mapping. In our automobile example let us move to the next step by adding the
following property to the CarVM model.

1. public double TotalPurchasePrice { get; set; }


While converting from Automobile this property should be populated by the summation of the AutomobileDM
properties Price and Tax. Following is the sample GetCar code highlighting the projection feature.

1. [HttpPost]
2. public ActionResult GetCar(string registrationNumber)
3. {
4. AutomobileDM automobile =
DataAccess.GetAutomobileFromDatabase(registrationNumber);
5.
6. //Create the mapping between AutomobileDM to CarVM
7. Mapper.CreateMap<AutomobileDM, CarVM>()
8. .ForMember(dest => dest.TotalPurchasePrice, opt => opt.MapFrom(src =>
src.Price + src.Tax));
9.
10. //Perform the conversion and fetch the destination view model
11. CarVM car = Mapper.Map<CarVM>(automobile);
12.
13. return View("GetCar", car);
14. }

Nested Models
What if the models are nested? This feature of AutoMapper is to do just that. Let us take our example to the next
level by making the domain and view model nested.

Create class InvoiceVM and add a property to CarVM with type InvoiceVM.

1. public class InvoiceVM


2. {
3. public int InvoiceId { get; set; }
4. public string Text { get; set; }
5. }
6. public InvoiceVM Invoice { get; set; }
Create class InvoiceDM and add a property to AutomobileDM with type InvoiceDM.

1. public class InvoiceDM


2. {
3. public int InvoiceId { get; set; }
4. public string Text { get; set; }
5. }
6. public InvoiceDM Invoice { get; set; }
Now let us go and modify the mapping in the GetCar method. Following is the sample code.

1. [HttpPost]
2. public ActionResult GetCar(string registrationNumber)
3. {
4. AutomobileDM automobile =
DataAccess.GetAutomobileFromDatabase(registrationNumber);
5.
6. //Create the mapping between AutomobileDM to CarVM
7. Mapper.CreateMap<AutomobileDM, CarVM>();
8. //As a next step define the mapping for the nested Invoice objects
9. Mapper.CreateMap<InvoiceDM, InvoiceVM>();
10.
11. //Perform the conversion and fetch the destination view model
12. //Note that here there is no explicit mentioning of the Invoice objects
13. CarVM car = Mapper.Map<CarVM>(automobile);
14.
15. return View("GetCar", car);
16. }
The important thing to note in all of the above examples is that only the CreateMapping call is getting altered and not
the Map method calls. So the customization will be required to be done only once in your application and the
conversion code will not require any changes to get these features implemented.

In addition to the above features there are many more, like type converters, value resolvers, Containers, inheritance
in the mapping, etc. Happy reading!

You might also like