I am new to automapper and am wondering how I could map a flat model into a Dto with 1 string property and IEnumerable
I have these classes
And I want to map this Model
public class DirectionModel
{
public string DirectionId { get; set; }
public decimal Longitude { get; set; }
public decimal Latitude { get; set; }
}
To this DTO classes
public class DirectionDto
{
public string DirectionId { get; set; }
public IEnumerable<CoordinateDto> Coordinates { get; set; }
}
public class CoordinateDto
{
public decimal Longitude { get; set; }
public decimal Latitude { get; set; }
}
Sample Input:
IEnum<DirectionModel>()
{
new DirectionModel() {DirectionId="id1", Longitude=1, Latitude=2},
new DirectionModel() {DirectionId="id1", Longitude=3, Latitude=4},
new DirectionModel() {DirectionId="id2", Longitude=5, Latitude=6}
}
This is the expecteed output:
IEnum<DirectionDto>()
{
new DirectionDto() {DirectionId="id1", IEnum<CoordinateDto>(){new CoordinateDto(){Longitude=1, Latitude=2}, new CoordinateDto(){Longitude=3, Latitude=4}}},
new DirectionDto() {DirectionId="id2", IEnum<CoordinateDto>(){new CoordinateDto(){Longitude=5, Latitude=6}}},
}
(edit: Corrected the sample input which may have caused confusion)
You can use AfterMap in AutoMapper, I prefer to use List instead of IEnumerable like this:
autoMapperConfig.CreateMap<List<DirectionModel>, List<DirectionDto>>()
.AfterMap((model, dto) =>
{
if (dto == null)
dto = new List<DirectionDto>();
if (model.Any())
{
dto.AddRange(model.GroupBy(x => x.DirectionId)
.Select(x => new DirectionDto()
{
DirectionId = x.Key,
Coordinates = x.ToList()
.Select(c => new CoordinateDto()
{
Latitude = c.Latitude,
Longitude = c.Longitude
}).ToList()
}).ToList());
}
});
And use it:
var lists = new List<DirectionModel>()
{
new DirectionModel() {DirectionId = "id1", Longitude = 1, Latitude = 2},
new DirectionModel() {DirectionId = "id1", Longitude = 3, Latitude = 4},
new DirectionModel() {DirectionId = "id2", Longitude = 5, Latitude = 6}
};
var dtos = _mapper.Map<List<DirectionModel>, List<DirectionDto>>(lists);