AutoMapper for Object Mapping in .NET 8

tamami.I Web Developer
3 min readJan 14, 2024

--

1. Scope of This Post

Facilitating Object Mapping via AutoMapper. The Basic Implementation Process in This Case”

2. Background

There is an application developed with ASP.NET Core 8 Web API. Data manipulation and model transfers between layers are redundant. I want to create mapping rules to make these processes more efficient.

3. Content

3–1. AutoMapper

AutoMapper is a library designed for object-to-object mapping based on specifications and rules. For example, using AutoMapper to reduce and standardize code, such as persisting DB data and transforming it through business logic into a model for API, or repeatedly inputting it into a ViewModel in MVC.

3–2. Setup

Install NuGet packages in the project.

AutoMapper
AutoMapper.Extensions.Microsoft.DependencyInjection

3–3. Implementation

a. Entity

Converting information fetched from the database into a Model format that suits the application.

Infrastructures layer

// Users.cs

public class Users:IDate
{
public int UserId { get; set; }
public required string UserName { get; set; }
public required string FirstName { get; set; }
public required string LastName { get; set; }
public required string Email { get; set; }
public DateTime Birthday { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public DateTimeOffset? DeletedAt { get; set; }
}

business layer

// User.cs

public class User
{
public int UserId { get; set; }
public required string FirstName { get; set; }
public required string LastName { get; set; }
public required string Email { get; set; }
public int BirthYear { get; set; }
public int BirthMonth { get; set; }
public int BirthDay { get; set; }
public string? OccupationName { get; set; }
}

b. Creating AutoMapper Profiles

Setting up mapping configurations for AutoMapper to map between two models. Detailing the procedures for data transfer from one model to another via AutoMapper.

・Setting up the mapping from Users to User using ‘CreateMap<Users, User>()’.

・Using the ForMember method to specify the mapping or exclusion of individual properties.

// AutoMapperProfile.cs

using AutoMapper;
using System;

public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<Users, User>()
.ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.UserId))
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.FirstName))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.LastName))
.ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.Email))
.ForMember(dest => dest.BirthYear, opt => opt.MapFrom(src => src.Birthday.Year))
.ForMember(dest => dest.BirthMonth, opt => opt.MapFrom(src => src.Birthday.Month))
.ForMember(dest => dest.BirthDay, opt => opt.MapFrom(src => src.Birthday.Day))
.ForMember(dest => dest.OccupationName, opt => opt.Ignore())
}
}

c. Setting Up Program.cs

AutoMapper is initialized during application startup and configured to be available throughout the entire application via dependency injection.

・Add AutoMapper to the service collection.

// AutoMapperConfig.cs

using AutoMapper;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

app.Run();

d. Executing the Mapping

Use the AutoMapper instance (IMapper) to perform mapping from a Users object to a User object.

// UserService.cs

using AutoMapper;

public class YourService
{
private readonly IMapper _mapper;

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

public User ConvertUsersToUser(Users users)
{
User user = _mapper.Map<User>(users);
return user;
}
}

4. In Summary

The use of AutoMapper simplifies and clarifies the rules for object interconversion. When frequently coding custom Converter code, Utilizing AutoMapper provides advantages in terms of code maintenance.

To access the Japanese version of this article, click [.NET8 AutoMapperを使用したObjectのマッピング]

--

--

tamami.I Web Developer
tamami.I Web Developer

Written by tamami.I Web Developer

I’m an engineer from Japan who loves coffee and mystery novels. I focus on cloud-native tech and share insights on tips, reflections, and hobbies.

Responses (2)