Thursday, 31 December 2015

AutoMapper in C#



Many times we need to map objects between UI/Domain or Service/Domain layers. Mapping the objects between them is very hectic. So, are there any simplest mechanisms by which I can map two objects? Is there is.
There is an AutoMapper class which you can use to map between two objects. This also provides option to do a custom mapping.

What is AutoMapper?
AutoMapper is a mapper between two objects. It maps two different entities by transforming an input object of one type to an output object of another type. It is very tough job to map two different entities and sometime it is even more hectic when it comes to testing. It can be anywhere in the application but in general it happens in UI/Domain or Service/Domain layers.
AutoMapper resolves that tough job by mapping it with proper convention and removes all the dirty works. Not only that, you can also customize the mapping with proper parameters.

How to Download AutoMapper?
AutoMapper is an open source library present in GitHub. To install the library, first install the NuGet Package Manager in your Visual Studio IDE. Once you installed the NuGet package manager, open the NuGet console and enter the following command to install the AutoMapper library:
 PM> Install-Package AutoMapper
 Once installed, verify the installation from your Visual Studio. If your project is open inside Visual Studio, it will automatically add the reference of the dll to the project.


How to Map two objects using AutoMapper?
Let’s begin with a console application and create two class named “Person” and “Employee”. Those two different entities have few properties in common but the Employee class will have an extra property.
In the below code snippet, you can see that, the Person class has four properties named Firstname, Lastname, Address and Contact. But Employee class has additional property named Fullname along with other properties.
Now suppose, as per requirement we have to map these two entities in our project. For the use of this demo, we will override the ToString() method of the Employee class so that when we call the ToString() method to the object, it returns the values of its properties in proper manner. 
Here is the complete code snippet of the same for your reference: 
public class Person
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Address { get; set; }
    public int Contact { get; set; }
}

public class Employee
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Fullname { get; set; }
    public string Address { get; set; }
    public int Contact { get; set; }

    // just overriding the ToString() method for simplicity
    public override string ToString()
    {
        return "Firstname: " + Firstname + Environment.NewLine +
               "Lastname: " + Lastname + Environment.NewLine +
               "Fullname: " + Fullname + Environment.NewLine +
               "Address: " + Address + Environment.NewLine +
               "Contact: " + Contact + Environment.NewLine;
    }
}

Let’s start with default mapping. In this case, we will map the two entities without providing additional parameters to it. The mapping will automatically map its properties based on the names of them. So in this case, it will have mappings between Firstname, Lastname, Address and Contact. As the Fullname property of Employee class does not have equivalent property in the Person class, it will not be mapped. 
To create the default mapping, call the Mapper.CreateMap<T1, T2>() with proper types. In this case, T1 will be Person and T2 will be Employee. Check out the below code snippet for quick reference: 
// create the mapping between two object types "Person" and "Employee"
Mapper.CreateMap<Person, Employee>();

// create the instance of Person with proper details
var person = new Person
{
    Firstname = "Kunal", Lastname = "Chowdhury",
    Address = "Tripura", Contact = 1234567890
};

// get the mapped instance of Person as Employee
var employee = Mapper.Map<Person, Employee>(person);

Console.WriteLine(employee.ToString());
 Finally call the Mapper.Map<T1, T2>(obj1) to get the mapped object of T2. Now when you print the object of Employee, you will see that it mapped all the properties except Fullname. We will see the output later in this post.
Now let’s do a little more complex operation. Here we will create custom mappings between two objects Person and Employee. The ForMember() and MapFrom() extensions do the same for you as mentioned in the below code snippet: 
// create custom mapping between two object types "Person" and "Employee"
Mapper.CreateMap<Person, Employee>().ForMember(emp => emp.Fullname,
                            map => map.MapFrom(p => p.Firstname + " " + p.Lastname));

// create the instance of Person with proper details
person = new Person
{
    Firstname = "Kunal", Lastname = "Chowdhury",
    Address = "Tripura", Contact = 1234567890
};

// get the mapped instance of Person as Employee
employee = Mapper.Map<Person, Employee>(person);

Console.WriteLine(employee.ToString());
Here in this case, it will map the equivalent properties of the both class and in addition to that, it will also map the Fullname property of the Employee class with the concatenated string of Firstname and Lastname properties as mentioned in the conditional parameter above. So now when you print the object of Employee, you will see the Fullname property automatically populated with Firstname and Lastname.
Here is the output of the above two code examples (both default mapping and custom mapping):


No comments:

Post a Comment