NET 6 - AutoMapper & Data Transfer Objects (DTOs) ? - DEV Community
NET 6 - AutoMapper & Data Transfer Objects (DTOs) ? - DEV Community
Mohamad Lawand
Posted on Oct 18, 2022
27
Intro
In this article we will be exploring AutoMapper and Data Transfer Objects (DTOs) in
.Net 6 Web Api. You can watch the full video on YouTube
https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e 1/11
21/9/24, 19:05 .NET 6 - AutoMapper & Data Transfer Objects (DTOs) 🗺 - DEV Community
Once we create our application we need to install the AutoMapper nuget package
into our application
Now that our nuget packages are installed we can start implementing and utilising
automapper.
In this example we will be building a simple api which will take DTOs which the client
sends and we will be utilising automapper to transform the objs into database obj
and vise versa when we get any obj from the data we will do some data
transformation to the client so we are not returning the full object
The first thing we need to do is to create a new folder called models which will
represent our database tables. Inside the root app directory we add this folder and
https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e 2/11
21/9/24, 19:05 .NET 6 - AutoMapper & Data Transfer Objects (DTOs) 🗺 - DEV Community
inside the Models folder we create a new class called Driver and we add the following
to it
namespace SampleMapper.Models;
Next we need to create a controller which will responsible for handling all of the
Driver requests. In order to make this example as simple as possible we will be using
an in-memory database instead of a full database.
using Microsoft.AspNetCore.Mvc;
using SampleMapper.Models;
namespace SampleMapper.Controllers;
[ApiController]
[Route("[controller]")]
public class DriversController : ControllerBase
{
private static List<Driver> drivers = new List<Driver>();
[HttpGet]
public IActionResult GetDrivers()
{
var items = drivers.Where(x => x.Status == 1).ToList();
return Ok(items);
}
https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e 3/11
21/9/24, 19:05 .NET 6 - AutoMapper & Data Transfer Objects (DTOs) 🗺 - DEV Community
[HttpPost]
public IActionResult CreateDriver(Driver data)
{
if(ModelState.IsValid)
{
drivers.Add(data);
[HttpGet("{id}")]
public IActionResult GetDriver(Guid id)
{
var item = drivers.FirstOrDefault(x => x.Id == id);
if(item == null)
return NotFound();
return Ok(item);
}
[HttpPut("{id}")]
public IActionResult UpdateDriver(Guid id, Driver item)
{
if(id != item.Id)
return BadRequest();
if(existItem == null)
return NotFound();
existItem.FirstName = item.FirstName;
existItem.LastName = item.LastName;
existItem.DriverNumber = item.DriverNumber;
existItem.WorldChampionships = item.WorldChampionships;
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult DeleteDriver(Guid id)
{
var existItem = drivers.FirstOrDefault(x => x.Id == id);
https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e 4/11
21/9/24, 19:05 .NET 6 - AutoMapper & Data Transfer Objects (DTOs) 🗺 - DEV Community
if(existItem == null)
return NotFound();
existItem.Status = 0;
return Ok(existItem);
}
}
Now let us see how we can transform this into a more optimised API and more user
friendly.
Inside the Models folder we create a new folder called DTOs, inside the DTOs folder
we create 2 new folders called
Will start by the incoming request. Inside the incoming folder we add the following
class
namespace SampleMapper.Models.DTOs.Incoming;
[HttpPost]
public IActionResult CreateDriver(DriverCreationDto data)
{
var _driver = new Driver()
{
Id = Guid.NewGuid(),
Status = 1,
DateAdded = DateTime.Now,
DateUpdated = DateTime.Now,
DriverNumber = data.DriverNumber,
FirstName = data.FirstName,
https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e 5/11
21/9/24, 19:05 .NET 6 - AutoMapper & Data Transfer Objects (DTOs) 🗺 - DEV Community
LastName = data.LastName,
WorldChampionships = data.WorldChampionships
};
if(ModelState.IsValid)
{
drivers.Add(_driver);
We can see that there is an advantage by using the Dto but it still not what we need,
we are still doing manual mapping between 2 objs.
Inside the rood directory of the application we are going to create a new folder called
Profiles, inside the folder we need to create a new class called DriverProfile and
update it to the following
using AutoMapper;
using SampleMapper.Models;
using SampleMapper.Models.DTOs.Incoming;
namespace SampleMapper.Profiles;
https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e 6/11
21/9/24, 19:05 .NET 6 - AutoMapper & Data Transfer Objects (DTOs) 🗺 - DEV Community
dest => dest.WorldChampionships,
opt => opt.MapFrom(src => src.WorldChampionships)
)
.ForMember(
dest => dest.Status,
opt => opt.MapFrom(src => 1)
)
.ForMember(
dest => dest.DriverNumber,
opt => opt.MapFrom(src => src.DriverNumber)
);
}
}
public DriversController(
ILogger<DriversController> logger,
IMapper mapper)
{
_logger = logger;
_mapper = mapper;
}
[HttpPost]
public IActionResult CreateDriver(DriverCreationDto data)
{
var _driver = _mapper.Map<Driver>(data);
if(ModelState.IsValid)
{
drivers.Add(_driver);
We also need to update our program.cs to inject AutoMapper into our DI container
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e 7/11
21/9/24, 19:05 .NET 6 - AutoMapper & Data Transfer Objects (DTOs) 🗺 - DEV Community
Inside Outgoing folder we need add a new class called DriverDto and add the
following
Now let us utilise this DTO by updating our profile class to the following
CreateMap<Driver, DriverDto>()
.ForMember(
dest => dest.Id,
opt => opt.MapFrom(src => Guid.NewGuid())
)
.ForMember(
dest => dest.FullName,
opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}")
)
.ForMember(
dest => dest.DriverNumber,
opt => opt.MapFrom(src => $"{src.DriverNumber}")
)
.ForMember(
dest => dest.WorldChampionships,
opt => opt.MapFrom(src => src.WorldChampionships)
);
And now let us update our controller to take advantage to the following
[HttpGet]
public IActionResult GetDrivers()
{
var items = drivers.Where(x => x.Status == 1).ToList();
https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e 8/11
21/9/24, 19:05 .NET 6 - AutoMapper & Data Transfer Objects (DTOs) 🗺 - DEV Community
Rahul R • Apr 9
Auth0 PROMOTED
https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e 9/11
21/9/24, 19:05 .NET 6 - AutoMapper & Data Transfer Objects (DTOs) 🗺 - DEV Community
Learn more
Mohamad Lawand
Code is Life. Crossfitter. Technical Architect. Just another human walking the earth!
https://youtube.com/c/mohamadlawand
LOCATION
Manchester, UK
WORK
Technical Architect
JOINED
Jul 25, 2019
AWS PROMOTED
https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e 10/11
21/9/24, 19:05 .NET 6 - AutoMapper & Data Transfer Objects (DTOs) 🗺 - DEV Community
Learn More
https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e 11/11