Imaging this scenario: We have an Employee object with many properties in it, and we want to display our Employee in a DataGrid or some other control. For this purpose we need a lighter version of Employee, let's call it EmployeeViewItem. A list of EmployeeViewItem will need to bind to our DataGrid.
public class Employee { public string Name { get; set; } public string Email { get; set; } public Address Address { get; set; } public string Position { get; set; } public bool Gender { get; set; } public int Age { get; set; } public int YearsInCompany { get; set; } public DateTime StartDate { get; set; } } public class Address { public string Country { get; set; } public string City { get; set; } public string Street { get; set; } public int Number { get; set; } } public class EmployeeViewItem { public string Name { get; set; } public string Email { get; set; } public string Address { get; set; } public string Position { get; set; } public string Gender { get; set; } public int Age { get; set; } public int YearsInCompany { get; set; } public string StartDate { get; set; } }Ok, so what we usually do? Something like this, right?
EmployeeViewItem viewItem = new EmployeeViewItem(); viewItem.Name = employee.Name; viewItem.Email = employee.Email; viewItem.Address = employee.Address.City + employee.Address.Street + employee.Address.Number; viewItem.Position = employee.Position; viewItem.Gender = employee.Gender == true ? "Man" : "Female"; viewItem.Age = employee.Age; viewItem.YearsInCompany = employee.YearsInCompany; viewItem.StartDate = employee.StartDate.ToShortDateString();
Quite annoying, isn't it? What if we could do this mapping automatically in some way? I hasten to please you - yes, you can map these two object automatically with AutoMapper!
As written on AutoMapper webpage - "AutoMapper is a simple little library built to solve a deceptively complex problem - getting rid of code that mapped one object to another."