In mvc automapper is very good approach to map the two different entities by transforming an input object of one type to an output object of another type. So most of time we have need to map uI/domain layer and services layer. Automapper also provide the Custom mapping.
Performance Issue
It is one of the situations where you should decide if the performance is so critical for you or no. I don't think that there are a lot of cases when you really need to choose manual mapping exactly because of performance issue.
Automapper Implementation
AutoMapper is a 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
So we have two entities Customer and customerModel
Public class Customer
{
Public int Id {get;set;}
Public string FirstName{get;set;}
Public string LastName{get;set;}
Public string Address {get;set;}
Public string City {get;set;}
}
Public class CustomerModel
{
Public int Id {get;set;}
Public string FirstName{get;set;}
Public string LastName{get;set;}
Public string Name {get;set;}
Public string Address {get;set;}
Public string City {get;set;}
}
So we have map these two entities by automapper
Mapper.CreateMap< Customer, CustomerModel >();
Now let’s do a little more complex operation. Here we will create a custom mappings between two objects Person and Employee. The ForMemer() and MapFrom() extensions do the same for you as mentioned in the below code snippet:
// create custom mapping between two object types "Customer" and "CustomerModel"
Mapper.CreateMap< Customer, CustomerModel >().ForMember(cst => cst.Name,
map => map.MapFrom(p => p.Firstname + " " + p.Lastname));
No comments:
Post a Comment