Automapper map a single object to an array of object

AutoMapper is an object mapper that helps you transform one object of one type into an output object of a different type.
We already learned in our article on Getting started with Automapper in ASP.NET Core.
Today in this article we shall see how to map a single object to an array of objects using Automapper.
We shall also see how to map an array of objects into a single object using an auto mapper.
Today in this article, we will cover below aspects,

In the above example, we are mapping array fields from Employee and [] Employee fields.
DI IMapper into the module
Dependency Injection of the IMapper interface is explained here already with more details,
Configuring Profile Instances
Here you need to create a class that inherits from the class Profile then please add your configuration of mapping into the Constructor.
Profiles are one of the best way of organizing all your mapping configurations in one place.
Below is Automapper profile for the array of object mapping.
public class SourceMappingProfile : Profile
{
public SourceMappingProfile()
{
CreateMap<Source, Destination>()
.ForMember(dest=>dest.Employee, o => o.MapFrom(src => new[] { src.Employee }))
.ForMember(dest => dest.Location, o => o.MapFrom(src => src.Address));
}
Here is a simplified example to perform Mapping object to an array of objects,
[HttpPost]
public IActionResult UpdateEmployee([FromBody] Source soureObject)
{
var destObject = _mapper.Map<Destination>(soureObject);
_logger.LogInformation("Mapping successful");
return Ok(destObject);
}

References:
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.