Mighty Badaboom
Mighty Badaboom

Reputation: 6155

Automapper: mapping between different types

Assuming I have a class structure like

public class Entity
{
    public List<EntityChild> Children { get; set; }
}

public class EntityChild
{
    public int Id { get; set; }
    public string Name { get; set; }
}

and I want to map Entity using AutoMapper to a class EntityDto and reverse.

public class EntityDto
{
    public List<int> EntityChildrenIds { get; set; }
}

I don't have any clue how to configure AutoMapper to map this properly in both directions. I know my Name property will be null when mapping from EntityDto to Entity but this would not be a problem.

Upvotes: 0

Views: 1234

Answers (2)

Augusto Ferbonink
Augusto Ferbonink

Reputation: 464

if .ReverseMap(), as mentioned by @knoop, didn't work maybe you should map it manually:

CreateMap<Entity, EntityDto>(MemberList.None)
    .ForMember(dest => dest.EntityChildrenIds, opts => opts.MapFrom(src => MapChildrenIds(src.Children)));


CreateMap<EntityDto, Entity>(MemberList.None)
    .ForMember(dest => dest.Children, opts => opts.MapFrom(src => MapChildren(src.EntityChildrenIds)));


private List<EntityChild> MapChildren(List<int> entityChildrenIds)
{
    var listEntityChild = new List<EntityChild>();

    foreach (var childId in entityChildrenIds)
        listEntityChild.Add(new EntityChild { Id = childId });

    return listEntityChild;
}
private List<int> MapChildrenIds(List<EntityChild> children)
{
    return children.Select(x => x.Id).ToList();
}

Upvotes: 0

user10608418
user10608418

Reputation:

For mapping both ways this configuration works for me:

var mapperConfiguration = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Entity, EntityDto>()
      .ForMember(dest => dest.EntityChildrenIds, opt => opt.MapFrom(src => src.Children))
      .ReverseMap();

    cfg.CreateMap<EntityChild, int>().ConvertUsing(child => child.Id);
    cfg.CreateMap<int, EntityChild>().ConvertUsing(id => new EntityChild
    {
      Id = id
    });
});

Since the properties have different names we need to configure that mapping.

Then just add general mappings from EntityChild to int and back again and we're done.

Upvotes: 1

Related Questions