When building full-stack applications with ASP.NET Core and Angular (or any frontend), you often deal with DTOs (Data Transfer Objects), ViewModels, and Entities. Mapping data between these objects manually can be repetitive, error-prone, and messy.
AutoMapper is a library that simplifies object-to-object mapping in ASP.NET Core. It automatically maps properties between objects with minimal configuration, making your backend code cleaner and maintainable.
This article explains how to use AutoMapper step by step in a full-stack application scenario.
What You Will Learn
What AutoMapper is and why it’s useful
How to install and configure AutoMapper in ASP.NET Core
How to create DTOs and map them to entities
How to integrate AutoMapper in your controllers and services
How AutoMapper improves frontend-backend communication
Best practices for clean, maintainable code
Step 1. Why Use AutoMapper
Suppose you have a User entity in your database:
public class User
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string PasswordHash { get; set; }
}
You don’t want to send the PasswordHash to the frontend. You may create a UserDto:
public class UserDto
{
public string FullName { get; set; }
public string Email { get; set; }
}
Without AutoMapper, you need to manually map:
var userDto = new UserDto
{
FullName = user.FullName,
Email = user.Email
};
For large objects or multiple endpoints, this becomes tedious. AutoMapper handles this automatically.
Part 1. Install Automapper
Run this command in your ASP.NET Core project:
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection
Part 2. Create DTOs (Data Transfer Objects)
DTOs are lightweight objects that contain only the data you want to expose to the frontend.
Example
public class UserDto
{
public string FullName { get; set; }
public string Email { get; set; }
}
public class CreateUserDto
{
public string FullName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
Part 3. Configure Automapper
Create a Mapping Profile:
MappingProfile.cs
using AutoMapper;
public class MappingProfile : Profile
{
public MappingProfile()
{
// Map User -> UserDto
CreateMap<User, UserDto>();
// Map CreateUserDto -> User
CreateMap<CreateUserDto, User>()
.ForMember(dest => dest.PasswordHash, opt => opt.MapFrom(src => BCrypt.Net.BCrypt.HashPassword(src.Password)));
}
}
Step 2: Register AutoMapper in Startup
Program.cs (ASP.NET Core 6/7+)
using AutoMapper;
var builder = WebApplication.CreateBuilder(args);
// Add AutoMapper
builder.Services.AddAutoMapper(typeof(Program));
// Add other services
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(...);
var app = builder.Build();
app.MapControllers();
app.Run();

Join the conversation! Your thoughts help the community grow.