This post shows you how to use AutoMapper in ASP.NET Core in C# .NET.
To practice this demo, you need to download and install AutoMapper from the Manage Nuget Packages or you can use the Nuget command line to install as shown below.
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection
Open your ConfigureServices.cs file, then add a configuration to call the AutoMapper required services like so
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper();
services.AddMvc();
}
Create a User and UserModelView classes as the following code
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
public class UserViewModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
Next, Create a UserProfile class to map data between User and UserViewModel classes
public class UserProfile : Profile
{
public UserProfile()
{
CreateMap<User, UserViewModel>();
}
}
Next, Create a User controller, then use the Map method to map data between User and UserViewModel classes
public class UserController : Controller
{
private readonly IMapper _mapper;
public UserController(IMapper mapper)
{
_mapper = mapper;
}
public IActionResult Index()
{
var user = new User(1, "Lucy", "Hynh", "[email protected]");
UserViewModel model = _mapper.Map(user);
return View(model);
}
}
You can use the IMapper interface to inject into your constructor, then call the Map method to map the type that you want to map or the object you would like to map.