We may have many situations, that we need to copy data from one object to another object. If an object of the Personal class has some data in it and need to copy that into another object of the Manager class.
Usually we use below style of coding to copy the Personal object property data to Manager object.
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace BestOfDotNet.AutoMapper { public class Program { public static void Main(string[] args) { Personal devObj=new Personal(); devObj.Id=101; devObj.FullName="Best Of Dot Net"; devObj.EmailId="bod@bestofdotnet.com"; //Use the created Map Manager mng=new Manager(); mng.Id=devObj.Id; mng.FullName=devObj.FullName; mng.EmailId=devObj.EmailId; //Test The Manager Detail Now Console.WriteLine("Manager Id :"+mng.Id.ToString()); Console.WriteLine("Manager FullName :"+mng.FullName.ToString()); Console.WriteLine("Manager EmailId :"+mng.EmailId.ToString()); Console.Read(); } } class Personal { public int Id{get;set;} public string FullName{get;set;} public string EmailId{get;set;} } class Manager { public int Id{get;set;} public string FullName{get;set;} public string EmailId{get;set;} } }
This is tedious and repetitive task in case the object has lot of properties.
In this situation, AutoMapper will plays very important role and helps to copy the data from one object to another object.
It sits in between Source and Destination objects like a bridge and maps the property data of the both the objects.
In order to use AutoMapper we would have to install it first from the Nuget Package Manager as explained below.
- Go to Manager Nuget Packages.... Option in the project.
- Search and install AutoMapper to your project.
- Include Required Library on the page.
using AutoMapper;
- Almost Done, we create a Mapper between the Personal and Manager class. This will be done using the following line.
var config = new MapperConfiguration(cfg => { cfg.CreateMap<Personal, Manager>(); }); IMapper mapper = config.CreateMapper();
- Let's copy the data from the object of Personal class into the object of Manager using the AutoMapper that we just created above.
Personal devObj = new Personal();
devObj.Id = 101; devObj.FullName = "Best Of Dot Net"; devObj.EmailId = "bod@bestofdotnet.com"; var dest = mapper.Map<Personal, Manager>(devObj);
- Its time to test the Manager Object
Console.WriteLine("Manager Id :" + dest.Id.ToString()); Console.WriteLine("Manager FullName :" + dest.FullName.ToString()); Console.WriteLine("Manager EmailId :" + dest.EmailId.ToString());
Result Shown below.