Featured

Getting Started with AutoMapper in ASP.NET 6

Last modified: March 11, 2022

Why we use this AutoMapper?

Without this we need to map each property of an object to another object one by one, which is lots of time consuming and error prone. AutoMapper solved this problem by automatically given property name is same between two objects.

1. Create Project

Create an ASP.NET Razor Page application.

createproject createproject createproject createproject

2. Install AutoMapper from Nuget Package

nuget

3. Create Objects
  • Project (e.g. entity from database table)
public class Project { public Guid Id { get; set; } public string Name { get; set; } public DateTime CreatedDate { get; set; } }
  • ProjectDTO (POCO transfer values between two projects). As you notice that ProjectDTO does not have CreatedDate, which show that we can hide properties of entity (DB Table) from UI.
public class ProjectDTO { public Guid Id { get; set; } public string Name { get; set; } }
4. Create Class Objects

Let's setup the AutoMapperConfiguration

Create a class file called AutoMapperProfile and inherit from Profile. In the constructor, we mapped objects to objects as shown below.

public class AutoMapperProfile : Profile { public AutoMapperProfile() { CreateMap<ProjectDTO, Project>().ReverseMap(); //reverse so the both direction } }
5. Configure in Program.cs
var config = new MapperConfiguration(cfg => { cfg.AddProfile(new AutoMapperProfile()); }); var mapper = config.CreateMapper(); builder.Services.AddSingleton(mapper);
6. Object to Object Example

Since we register mapper in Program.cs as DI, we can use it in constructor. Line 13, we create a Project object and we Line 14, we convert to ProjectDTO with the help of Mapper function

public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; private readonly IMapper _mapper; public IndexModel(ILogger<IndexModel> logger, IMapper mapper) { _logger = logger; _mapper = mapper; } public void OnGet() { var project = new Project(); var projectDTO = _mapper.Map<ProjectDTO>(project); //convert project object to projectDTO; } }