ASP.NET Core 8 with Automapper

AutoMapper is a popular .NET library that simplifies the process of mapping objects from one type to another. It automates the transformation of data between different object models, which is especially useful when dealing with Data Transfer Objects (DTOs) and domain models.

Sopheaktra

Eang Sopheaktra

September 07 2024 10:30 pm

0 636

Key Functions

  1. User's API
  2. Swagger for API's Endpoint

Getting Started

These instructions will get you to setup the project, install sdk and add package (CLI or Package manager console).

Prerequisites

  • Visual Studio 2022 or higher
  • .NET 8.x SDK

Installing

  1. Install .net SDK 8
    Download .NET SDK here.
  2. Create new Web API's project
dotnet new webapi –-name AutomapperWebAPIProject
  1. Add package to AutomapperWebAPIProject's project
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection

Languages and Tools

dotnet core  csharp  automapper 

Key Features of AutoMapper:

  • Automated Mapping: AutoMapper automatically maps properties between objects that have the same names and compatible types, reducing the need for manual copying.

  • Custom Mappings: You can define custom mappings for properties that don't have the same names or require special handling.

  • Profiles: AutoMapper uses profiles to organize and group mappings. A profile allows you to configure multiple mappings in one place.

  • Flattening: AutoMapper can map complex objects to flat DTOs by automatically flattening nested properties.

  • Conditional Mapping: You can conditionally map properties based on certain criteria or logic.

Advanced Features:

  1. Custom Type Converters: If you need more control over how properties are mapped, you can create custom type converters.

  2. Mapping Collections: AutoMapper can map collections, like lists or arrays, automatically.
  3. Reverse Mapping: You can enable reverse mapping to map back from the DTO to the original model.
  4. Ignore Properties: You can configure AutoMapper to ignore certain properties during the mapping process.

Create a Mapping Profile:

A mapping profile is a class where you define your object-to-object mappings.

using AutoMapper;
using AutomapperWebAPIProject.dto;
using AutomapperWebAPIProject.entity;

namespace AutomapperWebAPIProject.mapper {
    // public class CustomResolver : IValueResolver<UserEntity, UserDto, string>
    // {
    //     public string Resolve(UserEntity source, UserDto destination, string destMember, ResolutionContext context)
    //     {
    //         return $"{source.FirstName.ToUpper()} {source.LastName.ToLower()}";
    //     }
    // }
    // public class DateTimeTypeConverter : ITypeConverter<DateTime, string>
    // {
    //     public string Convert(DateTime source, string destination, ResolutionContext context)
    //     {
    //         return source.ToString("yyyy-MM-dd");
    //     }
    // }
    public class UserProfileMapper : Profile {
        public UserProfileMapper()
        {
            // Default mapping when property names are same
            CreateMap<UserEntity, UserDto>()
                .ForMember(dest => dest.Name, opt => opt.MapFrom(src => $"{src.LastName} {src.FirstName}"));
            
            //we can condition to not map if property is null
            // CreateMap<UserEntity, UserDto>()
            //     .ForMember(dest => dest.Name, opt => opt.Condition(src => src.FirstName != null && src.LastName != null));

            //we can ignore property to map
            // CreateMap<UserEntity, UserDto>()
            //     .ForMember(dest => dest.Name, opt => opt.Ignore());


            //we can using after map and assign any value to our property
            // CreateMap<UserEntity, UserDto>()
            //     .AfterMap((src, dest) => dest.Name = dest.Name.ToUpper());


            //we can using CustomResolver for mapping property
            // CreateMap<UserEntity, UserDto>()
            //     .ForMember(dest => dest.Name, opt => opt.MapFrom<CustomResolver>());


            //we can use include more derived source for map properties
            // CreateMap<UserEntity, UserDto>()
            //     .ForMember(dest => dest.Name, opt => opt.MapFrom(src => $"{src.LastName} {src.FirstName}"))
            //     .Include<DerivedSource, UserDto>();
            // CreateMap<DerivedSource, UserDto>();


            //we can use convert for mapping property
            // CreateMap<DateTime, string>().ConvertUsing<DateTimeTypeConverter>();


            // Mapping when property names are different
            //CreateMap<UserEntity, UserDto>()
            //    .ForMember(dest =>
            //    dest.Firstname,
            //    opt => opt.MapFrom(src => src.FirstName))
            //    .ForMember(dest =>
            //    dest.Lastname,
            //    opt => opt.MapFrom(src => src.LastName))
            //    .ReverseMap();
        }
    }
}

Register AutoMapper in the Service Container:

In your Startup.cs (for ASP.NET Core 5 and earlier) or Program.cs (for .NET 6 and later), register AutoMapper with the dependency injection (DI) container.

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

Inject IMapper and Use It:

Inject IMapper on minimal api such as:

app.MapGet("/users", static (IMapper mapper) =>
{
    var users =  Enumerable.Range(1, 5).Select(static index =>
        new UserEntity
        (
            Guid.NewGuid().ToString(),
            $"FirstName {index}",
            $"LastName {index}",
            Random.Shared.Next(18, 60),
            $"firstname.lastname.{index}@gmail.com"
        ))
        .ToArray();
    // var users =  Enumerable.Range(1, 5).Select(static index =>
    //     new DerivedSource
    //     (
    //         Guid.NewGuid().ToString(),
    //         $"FirstName {index}",
    //         $"LastName {index}",
    //         Random.Shared.Next(18, 60),
    //         $"firstname.lastname.{index}@gmail.com",
    //         $"DerivedProperty {index}"
    //     ))
    //     .ToArray();
    return mapper.Map<UserDto[]>(users);
})
.WithName("GetWeatherForecast")
.WithOpenApi();

Summary

AutoMapper is a powerful tool in ASP.NET Core for simplifying the mapping process between different object types, particularly when working with DTOs and domain models. By reducing boilerplate code and providing a flexible mapping system, it helps maintain cleaner and more maintainable codebases. Download the source code for the sample.

Comments

Subscribe to our newsletter.

Get updates about new articles, contents, coding tips and tricks.

Weekly articles
Always new release articles every week or weekly released.
No spam
No marketing, share and spam you different notification.
© 2023-2025 Tra21, Inc. All rights reserved.