.NET  

How to Map DTOs Using AutoMapper in .NET with Example

Introduction

When you build applications using .NET, especially ASP.NET Core Web APIs, you often work with multiple layers like database models, business logic models, and API response objects. These objects usually look similar, but they are not exactly the same.

For example, your database model may contain sensitive data like passwords or internal fields, but your API response should not expose that information.

This is where DTOs (Data Transfer Objects) and AutoMapper come into the picture.

Instead of manually copying data from one object to another again and again, AutoMapper helps you do it automatically with clean and maintainable code.

In this article, we will understand everything step by step in simple words with practical examples so that even beginners can easily understand how DTO mapping works in .NET.

What is a DTO (Data Transfer Object)?

A DTO is a simple object whose main purpose is to transfer data from one layer of an application to another.

It does not contain any business logic. It only contains the data that you want to send or receive.

Real-life example

Think of ordering food online.

  • The kitchen (database) has full details like ingredients, cost, supplier, etc.

  • But what you see in the app (DTO) is only name, price, and description

You don’t need internal kitchen data, only what is relevant to you.

That is exactly what a DTO does in software.

Why DTOs are important

  • They protect sensitive data

  • They reduce unnecessary data transfer

  • They make APIs cleaner and faster

Why Use AutoMapper in .NET?

Now imagine you have 20 properties in a class. Writing mapping code manually for each property becomes boring and repetitive.

Without AutoMapper

You have to write code like this every time:

  • Assign each property one by one

  • Update mapping when model changes

  • Risk of missing fields or making mistakes

With AutoMapper

  • It automatically maps properties with the same names

  • You write mapping logic only once

  • Your code becomes shorter and easier to read

Real-world analogy

Manual mapping is like copying data from one notebook to another line by line.

AutoMapper is like taking a photocopy instantly.

Install AutoMapper in .NET Project

To use AutoMapper, you first need to install it in your project.

You can install it using NuGet Package Manager or command line.

Using Package Manager Console

Install-Package AutoMapper
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

These packages help you:

  • Use AutoMapper core functionality

  • Integrate it with ASP.NET Core dependency injection

Step-by-Step Example: Mapping DTO using AutoMapper

Let’s understand this with a simple and practical example.

Step 1: Create a Domain Model

This represents your database or core business object.

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

Here, Password is sensitive information and should not be exposed.

Step 2: Create a DTO

This is what you will send to the client (API response).

public class UserDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

Notice that we removed the Password field.

This is how DTO helps in securing your application.

Step 3: Create Mapping Profile

A mapping profile is where you define how one object maps to another.

using AutoMapper;

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<User, UserDto>();
    }
}

What this does

  • It tells AutoMapper how to convert User to UserDto

  • It automatically maps properties with the same name

Step 4: Register AutoMapper in Application

In .NET 6 or later, you register AutoMapper in Program.cs.

builder.Services.AddAutoMapper(typeof(MappingProfile));

Why this is needed

  • It enables dependency injection

  • Makes AutoMapper available across your application

Step 5: Use AutoMapper in Service or Controller

Now you can use AutoMapper wherever needed.

using AutoMapper;

public class UserService
{
    private readonly IMapper _mapper;

    public UserService(IMapper mapper)
    {
        _mapper = mapper;
    }

    public UserDto GetUser()
    {
        var user = new User
        {
            Id = 1,
            Name = "John",
            Email = "[email protected]",
            Password = "123456"
        };

        var userDto = _mapper.Map<UserDto>(user);
        return userDto;
    }
}

What is happening here

  • We create a User object

  • AutoMapper converts it into UserDto

  • Sensitive data (Password) is automatically excluded

Before vs After Using AutoMapper

Without AutoMapper

var userDto = new UserDto
{
    Id = user.Id,
    Name = user.Name,
    Email = user.Email
};

With AutoMapper

var userDto = _mapper.Map<UserDto>(user);

Key difference

  • Less code

  • Better readability

  • Easier maintenance

Advanced Mapping Scenarios

Sometimes real projects are not that simple.

Custom Mapping

CreateMap<User, UserDto>()
    .ForMember(dest => dest.Name,
               opt => opt.MapFrom(src => src.Name.ToUpper()));

Here, we are modifying data during mapping.

Ignoring Properties

CreateMap<User, UserDto>()
    .ForMember(dest => dest.Email, opt => opt.Ignore());

This is useful when you don’t want certain fields in output.

Real-World Use Case

Let’s say you are building an e-commerce application.

  • Product Entity → contains cost price, supplier info

  • Product DTO → contains name, selling price, description

Using AutoMapper:

  • You safely expose only required data

  • You avoid accidental data leaks

  • Your API remains clean and optimized

Advantages of AutoMapper

  • Reduces repetitive code

  • Improves code readability

  • Centralized mapping logic

  • Easy to update when models change

  • Works well in large applications

Disadvantages of AutoMapper

  • Can hide logic, making debugging slightly harder

  • Overuse may reduce clarity in small projects

  • Initial learning curve for beginners

When Should You Use AutoMapper?

Use it when

  • You have multiple models and DTOs

  • Your application is growing

  • You want clean and scalable architecture

Avoid it when

  • Your project is very small

  • Mapping is very simple

  • You need full manual control

Summary

AutoMapper makes object-to-object mapping in .NET simple, clean, and efficient. Instead of writing repetitive code, you define mapping rules once and reuse them throughout your application. By using DTOs along with AutoMapper, you can protect sensitive data, improve performance, and keep your code easy to manage. Start with basic mapping and gradually explore advanced features as your project grows, and you will see a significant improvement in both development speed and code quality.