Automapper mapping list becomes 0

2019-02-21 22:28发布

问题:

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; }
}

回答1:

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.



回答2:

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


回答3:

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);