9

I'm mapping a list to another list with Automapper, but it seems that my items are not copied.

Here is my code:

var roles = userRepo.GetRoles(null).ToList();
Mapper.CreateMap < List<Domain.Role>, List<Role>>();
var mappedRole = Mapper.Map<List<Domain.Role>, List<Role>>(roles); //the count is 0, list empty :(
Mapper.AssertConfigurationIsValid();
  1. No exceptions were thrown.
  2. All properties has the same names.

Domain.Role

public class Role
{
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public List<User> Users { get; set; }
}

Role

public class Role
{
    public int RoleId { get; set; }
    public string RoleName { get; set; }
}
Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

3 Answers3

39

Don't create maps between lists and array, only between the types:

Mapper.CreateMap<Domain.Role, Role>();

and then:

var mappedRole = Mapper.Map<List<Domain.Role>, List<Role>>(roles);

AutoMapper handles lists and arrays automatically.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I am experiencing some weird behavior while using the AutoMapper. For some reason, while mapping between two lists, the first item seems to be repeated n times in the destination list. I created an article here : http://stackoverflow.com/questions/17268362/automapper-for-a-list-scenario-only-seems-to-repeat-mapping-the-first-object-in asking about this issue. I think I am using the AutoMapper according to the specs, though I am a newbie to it. Please review and let me know your thoughts. – user1790300 Jun 24 '13 at 17:25
0

In my case, I had the (parent) type mapping configured correctly but I didn't add the mappings for the child records, so for this:

class FieldGroup
{
    string GroupName { get; set; }
    ...
    List<Field> fields { get; set; }
}

I had to add the second mapping:

cfg.CreateMap<FieldGroup, FieldGroupDTO>();
cfg.CreateMap<Field, FieldDTO>(); << was missing
IngoB
  • 2,552
  • 1
  • 20
  • 35
0

Avoid adding Collections in your mapper configuration. Make sure you add all the types(classes). I had errors when collections were not in the config, but that was because all types were not included. Bit misleading but that's where the problem lies. Point is, remove all collections from mapper config and add all classes only. Add collections when doing the actual transformation ie. call to mapper.Map.

        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Infrastructure.Entities.Pet, Domain.Model.Pet>();
            cfg.CreateMap<Infrastructure.Entities.Owner, Domain.Model.Owner>().ReverseMap();
        });

        var mapper = config.CreateMapper();
        var domainPetOwners = mapper.Map<List<Domain.Model.Owner>>(repoPetOwners);
kodi
  • 161
  • 1
  • 5