Home > Blockchain >  How to map from flat object to list using Automapper c# .net6?
How to map from flat object to list using Automapper c# .net6?

Time:09-10

I'm trying to map a flat object to a list. The Id gets mapped properly, but the list is always empty. I have used reverse mapping for the ListItem in destination.

What is wrong with this code or missing please?

using AutoMapper;

MapperConfiguration config = new MapperConfiguration(x =>
{
    x.CreateMap<Origin, Destination>();
    x.CreateMap<Destination, NonListItem>()
    .ReverseMap()
    .ForPath(d => d.ListItem, o => o.MapFrom(s => new List<ListItem> {
        new ListItem
        {
            ListInt = s.NonListInt,
            ListStr = s.NonListStr
        }
    }));
});

var origin = new Origin();
origin.Id = 12345;
origin.NonListItem.NonListInt = 54321;
origin.NonListItem.NonListStr = "This is a test";

IMapper mapper = new Mapper(config);
var destination = mapper.Map<Destination>(origin);

Console.ReadKey();

//############################################################### 

public class Origin
{
    public NonListItem NonListItem { get; set; } = new NonListItem();
    public int Id { get; set; }
}

public class NonListItem
{
    public int NonListInt { get; set; }
    public string? NonListStr { get; set; }

}

public class Destination
{
    public int Id { get; set; }
    public List<ListItem> ListItem { get; set; } = new List<ListItem>();
}

public class ListItem
{
    public int ListInt { get; set; }

    public string? ListStr { get; set; }
}

CodePudding user response:

Mapping from Destination to NonListItem is not needed. Just configure the Origin to Destination mapping.

MapperConfiguration config = new MapperConfiguration(x =>
{
    x.CreateMap<Origin, Destination>()
       .ForMember(dest => dest.ListItem, opt => opt.MapFrom(src => new List<ListItem>
       {
           new ListItem
           {
                ListInt = src.NonListItem.NonListInt,
                ListStr = src.NonListItem.NonListStr
           }
       }));
});
  • Related