AutoMapper in ASP.NET Core MVC
Automapper is open source, so you can get it with the nuget package manager. The following is a command to install the AutoMapper in your application.
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection
After installation, you can view the AutoMapper under packages.
using AutoMapper;
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(typeof(Startup));
services.AddControllersWithViews();
}
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Grade { get; set; }
}
This class is a StudentViewModel class that is going to get value from the student class.
public class StudentViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
The StudentViewModel class has only three property values. But there are five values in the Student class.When we map the value from the Student object, it will map the appropriate property values.
Sometimes the destination object may have additional values.
AutoMapping.cs
using AutoMapper;
public class AutoMapping : Profile
{
public AutoMapping()
{
CreateMap<Student, StudentViewModel>();
}
}
The following is a home controller code. Here the IMapper interface is injected into the HomeController constructor. In the Index action method, values are assigned to Student class. Next the using _mapper.map function stud object values are mapped to the studModel.
public class HomeController : Controller
{
private readonly IMapper _mapper;
public HomeController(IMapper mapper)
{
_mapper = mapper;
}
public IActionResult Index()
{
Student stud = new Student() {
Id =1,
FirstName = "Peter",
LastName = "Parker",
Age = 15,
Grade = "Tenth grade"
};
StudentViewModel studModel = _mapper.Map<Student,
StudentViewModel>(stud);
return View(studModel);
}
The following is a view code to display the result in webpage
@model StudentViewModel
<h4>AutoMapper Demo</h4>
<table>
<tr>
<td>First Name:</td>
<td>
<b>@Model.FirstName</b> </td>
</tr>
<tr>
<td> Last Name: </td>
<td>
<b>@Model.LastName</b> </td>
</tr>
<tr>
<td>Age:</td>
<td><b>@Model.Age</b> </td>
</tr>
</table>
We can’t always expect the source object property name and the destination
property name should be the same.
public class StudentViewModel
{
public string FrstNm { get; set; }
public string LstNm { get; set; }
public int Age { get; set; }
public string Course { get; set; }
}
To map this different property value, you need to map the property using the ForMember method in the profile.
public class AutoMapping : Profile
{
public AutoMapping()
{
CreateMap<Student,
StudentViewModel>()
.ForMember(x=>x.FrstNm,
opt =>
opt.MapFrom(src=>src.FirstName))
.ForMember(x
=> x.LstNm,
opt =>
opt.MapFrom(src => src.LastName));
}
}
I hope this article will help you. Keep coding.
Comments
Post a Comment