Automapper display list becomes 0

I map the list to another list using Automapper, but it seems that my objects are not being 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(); 
  • There were no exceptions.
  • All properties have the same name.

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; } } 
+7
source share
3 answers

Do not create maps between lists and an array, only between types:

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

and then:

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

AutoMapper automatically processes lists and arrays .

+32
source

In my case, I set up the display of the (parent) type correctly, but I did not add a mapping for the child entries, so for this:

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

I had to add a second mapping:

 cfg.CreateMap<FieldGroup, FieldGroupDTO>(); cfg.CreateMap<Field, FieldDTO>(); << was missing 
0
source

Avoid adding collections to your mapper configuration. Make sure you add all types (classes). I had errors when the collections were not in the config, but this was because all types were not included. Bit misleading, but where's the problem. Point is, remove all collections from the mapper configuration and add only all classes. Add collections when performing the actual conversion, i.e. call 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); 
0
source

All Articles