1

I am mapping with automapper 5.2 from Dto to Model and from Model to Dto. But the problem I have, that have 0 elements when I do the mapping. The two entities are the same.

AutoMapperConfiguration.cs

public class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(x =>
        {
            x.CreateMap<PaisDto, Pais>().ReverseMap();
            x.CreateMap<List<PaisDto>, List<Pais>>().ReverseMap();
            x.CreateMap<Pais, PaisDto>().ReverseMap();
            x.CreateMap<List<Pais>, List<PaisDto>>().ReverseMap();
        });
    }
}

PaisService.cs

public IEnumerable<PaisDto> GetAll()
{
    AutoMapperConfiguration.Configure();
    List<PaisDto> dto = new List<PaisDto>();
    IEnumerable<Pais> paises = _paisRepository.GetPaisAll();
    dto = Mapper.Map<List<Pais>,List<PaisDto>>(paises.ToList());
    return dto.ToList();
}

what can happen?

Richard
  • 29,854
  • 11
  • 77
  • 120
ascariz
  • 13
  • 1
  • 4
  • Does the object have any elements before you do the mapping? – Alex Mar 01 '17 at 15:48
  • you use automapper 5.2 but also the static Mapper? if you plan on updating this you might want to tweek the code a little bit, https://lostechies.com/jimmybogard/2016/01/21/removing-the-static-api-from-automapper/ the article shows how the code changes, that way you also have the mapperConfig that is described in my answer. – Axel Bouttelgier Mar 01 '17 at 15:56
  • 1
    Not an answer, but you should only call `Mapper.Initialize` once at the start of your app, not every time you use it. – stuartd Mar 01 '17 at 16:26

2 Answers2

1

Not sure if this is what you are looking for but you can create a map for the single pais/paisDto

and when you want to map a list you can use the EF6 extention from automapper themselves

https://www.nuget.org/packages/AutoMapper.EF6/

then you can just use

.ProjectTo<TDestination>(mapperConfig) 

on the list that needs to be mapped

Axel Bouttelgier
  • 173
  • 1
  • 12
1

You don't need to map from a list to a list - Automapper knows about lists, you just need to tell it about the individual items:

Mapper.Initialize(x =>
{
    x.CreateMap<Pais, PaisDto>().ReverseMap();
});

Then it can map a list by itself:

IEnumerable<Pais> paises = _paisRepository.GetPaisAll();
List<PaisDto> dto = Mapper.Map<List<PaisDto>>(paises);
return dto;

You also don't need to call .ToList on lists, that just makes another copy.

Richard
  • 29,854
  • 11
  • 77
  • 120