Keep your code clean with AutoMapper

Explaining How to use AutoMaptter with ASP.NET Core web App

Keep your code clean with AutoMapper

1. What is AutoMapper?

2. Why do we need AutoMapper?

public class Student
{
public string StuId { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
public class StudentDTO
{
public string StuId { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
public Student MapObjects(StudentDTO stud)
{
return new Student(){
stuId = stud.stuID,
name = stud.FullName,
age = stud.Age,
city = stud.City,
};
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
}
public class Student
{
public string StuId { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
public class StudentDTO
{
public string StuId { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
public class AutoMapProfile : Profile
{
public AutoMapProfile()
{
CreateMap<StudentDTO, Student>();
}
}

4. Map two objects with IMapper

[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
private readonly IMapper _mapper;public StudentController(IMapper mapper)
{
_mapper = mapper;
}
[HttpGet]
public Student Get()
{
StudentDTO studentDTO = new StudentDTO(){
StuId = "STU001"
Name = "Yohan",
Age = 25,
City = "Kalutara",
};
return _mapper.Map<Student>(studentDTO);
}
}

5. Few cool features of AutoMapper

public class Student
{
public string StuId { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
public class StudentDTO
{
public string StuId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
public class AutoMapProfile : Profile
{
public AutoMapProfile()
{
CreateMap<StudentDTO, Student>().
ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name));
}
}
public class AutoMapProfile : Profile
{
public AutoMapProfile()
{
CreateMap<StudentDTO, Student>()
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.isTeen, opt => opt.MapFrom(src => src.Age < 18 ? true : false));
}
}

An Undergraduate of Sabaragamuwa University of Sri Lanka.