Using AutoMapper in C#

Ahteshamax
Posted by in C# category on for Beginner level | Points: 250 | Views : 2691 red flag
Rating: 4.5 out of 5  
 2 vote(s)

In this article will try to understand how to use Automapper in C#.

AutoMapper is used in Visual Studio which is reusable component where it helps to copy data from one object type to other object type. Basically it does mapping automatically incase if naming convention of property name found to be same.

Let us try to understand it in more detail from the below Visual Studio code, here we have Class Person and Class Student. If we want to copy data or transfer data from one class to other we have traditional way of doing it.

First create object “per” of Class Person with following line of code

Person per = new Person();

With some data like First Name and Last Name.

per.FirstName = "Sadgopal";
per.LastName = "Khurana";

Next it to create object “std” of Class Student with following line of code

Student std = new Student();

And then transfer data from source Person Class to destination Student Class is done.

std.FirstName = per.FirstName;
std.LastName = per.LastName;

Tomorrow what if the data i.e. property in the class is increased then writing code for each property data moving from source class to destination class would be more hectic job. In other words mapping of code is done again and again for source and destination. What if we get a solution where we can keep mapping code centrally and then it used again and again.

Here is where AutoMapper fits and sits in between source class and destination class. With this it will map the property data of both the objects when found property name to be same in source and destination class.

AutoMapper is not in-build within Visual Studio it has to be installed from the NuGet packages, in order to do installation do a right click Solution > Manage NuGet Packages as shown in the image down below.

It will open a new pane within Visual Studio with name “NuGet – Solution” as shown in the image down below.

On this pane now click in the “Browse” tab and on the search box type “AutoMapper” here on the search list you will find many AutoMapper’s. Click on the “AutoMapper by Jimmy Bogard”.

After you click on the right side select existing project “ConsoleApplication3” by doing a checkmark on it and then below click on “Install”.

After you click on install it will prompt a preview window as shown in the image below which says that this installation will make changes internally to the existing selected project “ConsoleApplication”. In order to proceed installation click OK. Once installation is done you will see details of successful AutoMapper installation down below in “Output” window.

To use installed AutoMapper next is to import name space by typing text “using AutoMapper” as shown in the below image. While writing text to import namespace intellisense will show autocomplete text which states that AutoMapper is successfully installed.

Once Automapper namespace is imported, next creating Automapper is two steps process where first we have to create map and then use that map.

Create Map

Before we create map keep existing class Person created object “per” and its properties “FirstName” and “LastName” as it is.

Now create map by using following line of code

Mapper.CreateMap();

Here use mapper code with code line “CreateMap” between class Person and class Student.

Using Created Map

Create object “std” of class Student and use created map with object of class Person.

Student std = Mapper.Map(per);

After you finished writing the code Build entire solution to check for coding error if any. After Build is successfully done do place and debug point and run the program when you hover mouse over the created map you will find the properties value of class Person in class Student.

Please Note: Here you will find that mapping of each property first name and last name was taken automatically between class Person and class Student. This is because naming convention and property name are same in both class.

Consider the following image where we have property name different for both class Person and class Student. In class Person property name for First name is “FirstName” and Last name is “LastName” while for class Student property name for First name is “FName” and Last name is “LName”.

Now here, we have to write each property mapping code for each class under our “Create Map” as shown below. We have to include “ForMember” by mentioning explicitly source is “FirstName”/”LastName” of class Person and destination is “FName/LName” of class Student.

.ForMember(dest => dest.FName, opt => opt.MapFrom(src => src.FirstName))
.ForMember(dest => dest.LName, opt => opt.MapFrom(src => src.LastName))

With above line of code mapping for each property will done.

In this way we can use AutoMapper which is reusable component on our Visual Studio. Hope that the practical of AutoMapper is understood by the reader.

Also we would like to share that if you want to learn C# with full blown project below is starting first video from that series. Do follow this series and practice it your most of the fundamentals with practical knowledge will also be covered. Hope that you will learn and gain the maximum from it.

Page copy protected against web site content infringement by Copyscape

About the Author

Ahteshamax
Full Name: Ahtesham Shaikh
Member Level: Bronze
Member Status: Member
Member Since: 10/3/2016 2:36:04 AM
Country: India
Ahtesham Shaikh
http://www.learnmsbitutorials.net/
Hey Friends, Myself Ahtesham a coder, writer & technical supporter for IT world and for my company Questpond. Having 10+ years of experience in microsoft technologies like WCF, WPF, MVC, Sharepoint, AngularJS, MSBI, Excel 2000 - 2013, Powerpoint, C#, SQL Server and so on. I just find myself happy and satisfy by doing this job. Apart from profession love reading novels and other digital network books. I'm a faculty at Questpond and do take trainings on c#, object oriented programming, msbi, sharepoint, mvc, mvc, angularJS and so on. Feel free get in touch me for one-to-one trainings, offline trainings @Andheri Mumbai, Online training via microsoft live meeting.

Login to vote for this post.

Comments or Responses

Posted by: Spothuganti on: 3/15/2017 | Points: 25
Hi,

The static version of CreateMap method was deprecated in 4.2, then removed from the API in version 5.0.

The code should be modified as mentioned in the below URL:

http://stackoverflow.com/questions/38194012/automapper-mapper-does-not-contain-definition-for-createmap

Person per = new Person();
per.FirstName = "Siddi";
per.LastName = "Khadar";


var config = new MapperConfiguration( (cfg => {
cfg.CreateMap<Person, Student>();
}));

IMapper mapper = config.CreateMapper();
var dest = mapper.Map<Person, Student>(per);


Login to post response

Comment using Facebook(Author doesn't get notification)