November 8, 2019 11:20 by
Peter
At this moment, I will show you How to Use Automapper with ASP.NET MVC Application. Automapper could be a convention primarily based object - object mapper. it's offered in GitHub. Here I make a case for about a way to use Automapper to map between domain model objects and think about model objects in ASP.NET MVC applications. Install Automapper to the project through Nuget.
Consider there's a powerfully typed view that expects a model object of type EmployeeViewModel. thus after querying with the Emplyee model object, we want to map this to EmployeeViewModel object.
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
}
And my employee view model
public class EmployeeViewModel
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
}
The use of AutoMapper
AutoMapper is designed within the web project. to form this more maintainable, create a folder (say Mappings) within the solution. Here we will produce 2 profile classes. One for mapping from domain model object to look at model object and another one for reverse mapping.
public class DomainToViewModelMappingProfile : Profile
{
public override string ProfileName
{
get { return "DomainToViewModelMappings"; }
}
protected override void Configure()
{
Mapper.CreateMap<Employee, EmployeeViewModel>();
}
}
public class ViewModelToDomainMappingProfile : Profile
{
public override string ProfileName
{
get { return "ViewModelToDomainMappings"; }
}
protected override void Configure()
{
Mapper.CreateMap<EmployeeViewModel, Employee>();
}
}
Now create a configuration class within Mappings folder.
public class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(x =>
{
x.AddProfile<DomainToViewModelMappingProfile>();
x.AddProfile<ViewModelToDomainMappingProfile>();
});
}
}
And then call this configuration from global.asax.
AutoMapperConfiguration.Configure();
And from the controller simply map the employeeObject (domain model object) to employeeViewModelObject (view model object).
var employeeViewModelObject = Mapper.Map<Employee, EmployeeViewModel>(employeeObject);
In advanced situation we will even customise the configuration. for instance we will map a specific property from source to destination.
Mapper.CreateMap<X, XViewModel>()
.ForMember(x => x.Property1, opt => opt.MapFrom(source => source.PropertyXYZ));
Automapper provides extremely an improved and straightforward way to map between objects.