In ASP.NET MVC 5 with Web API, AutoMapper is a popular library used to map objects from one type to another, reducing boilerplate code and enhancing maintainability, especially in applications with complex data structures. It allows you to map between data transfer objects (DTOs) and domain models automatically.
Steps to set up AutoMapper in an ASP.NET MVC 5 Web API project:
1. Install AutoMapper via NuGet
First, you need to install the AutoMapper package into your project. You can do this by running the following command in the NuGet Package Manager Console:
Install-Package AutoMapper
Alternatively, you can use the NuGet package manager GUI to search for and install AutoMapper.
2. Create DTOs and Domain Models
Define your domain models (entities) and Data Transfer Objects (DTOs). For example:
Domain Model (e.g., Customer
):
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
DTO (e.g., CustomerDTO
):
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
}
3. Create AutoMapper Profile
Create a profile class to configure how AutoMapper should map your models to DTOs. For instance:
public class MappingProfile : Profile { public MappingProfile()
{
// Mapping from Customer to CustomerDTO
CreateMap<Customer, CustomerDTO>() .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.FirstName + " " + src.LastName));
}
}
4. Initialize AutoMapper
In your Web API project, the mapping configuration should be initialized in the Application_Start
method within the Global.asax.cs
file. Add the following code to configure AutoMapper globally:
protected void Application_Start()
{
// Register AutoMapper profiles
Mapper.Initialize(cfg => cfg.AddProfile
// Other Web API configurations
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Alternatively, in newer versions of ASP.NET Core, AutoMapper could be injected through dependency injection, but in MVC 5/Web API 2, initialization like this works fine.
5. Use AutoMapper in Your Controllers
You can now use AutoMapper to map models to DTOs in your Web API controllers.
For example:
{
// Assume dbContext is already defined for fetching data
private readonly ApplicationDbContext _context = new ApplicationDbContext();
// GET api/customers
public IHttpActionResult GetCustomers()
{
var customers = _context.Customers.ToList();
// Map from Customer to CustomerDTO
var customerDtos = Mapper.Map<List<CustomerDTO>>(customers);
return Ok(customerDtos);
}
// GET api/customers/{id}
public IHttpActionResult GetCustomer(int id)
{
var customer = _context.Customers.Find(id); if (customer == null)
{
return NotFound();
}
// Map from Customer to CustomerDTO
var customerDto = Mapper.Map<CustomerDTO>(customer);
return Ok(customerDto);
}
}
6. Testing
{ Id = c.Id, FullName = c.FirstName + " " + c.LastName, Email = c.Email }) .ToList();
This avoids loading unnecessary data into memory before mapping and can be more efficient.
With this setup, AutoMapper will help you map objects and reduce the manual conversion code in your Web API controllers.