Search code examples
c#automapperautomapper-3

Map a dozen of hierarchical objejcts with AutoMapper to DTOs


I have a hierarchy of 12 entity framework objects.

I have also for each entity a DTO created.

I want to send the DTOs over the wire.

I have to use the DTO-approach.

How would you map this amount of objects with Automapper?

Do I have to use 12 times the AutoMapper.Map method?

UPDATE

I get this error now:

{"Missing type map configuration or unsupported mapping.\r\n\r\n....
I have an NumberEntity.cs with 3 complex properties which I want to map to

a NumberDTO.cs with 3 complex properties.

Is that not possible? Do I have to setup an extra mapping for complex classes within a class?


Solution

  • No, you have to create a mapping for each DTO in config.

    Let's say you have a Person.cs, Address.cs, Car and User in your Entities

    public class User
    {
    public int UserId {get;set;}
    public string UserName {get;set;}
    
    public PersonDTO Person {get;set;}
    }
    
    public class Person
    {
    public int PersonID {get;set;}
    public string Name {get;set;}
    
    public Address Address {get;set;}
    public Car Car {get; set;}
    
    }
    

    So you also have PersonDTO, AddressDTO, and CarDTO

    e.g.

        public class UserDTO
        {
        public int UserId {get;set;}
        public string UserName {get;set;}
    
    // HERE IF YOU HAVE:
    // public PersonDTO MyPerson {get;set;}
    // IT WILL NOT MAP
    // Property Names should match
    
        public PersonDTO Person {get;set;}
    
        }
    
    
    public class PersonDTO
    {
       public int PersonID {get;set;}
       public string Name {get;set;}
    
       public AddressDTO Address {get;set;}
       public CarDTO Car {get;set;}
    
    }
    

    Your class where you have all Mappings defined.

    public class MapperConfig
    {
      public static void CreateMappings()
      {
            Mapper.CreateMap<UserDTO, Entities.User>().ReverseMap();
            Mapper.CreateMap<PersonDTO, Entities.Person>().ReverseMap();
    
            Mapper.CreateMap<AddressDTO, Entities.Address>().ReverseMap();
            Mapper.CreateMap<CarDTO, Entities.Car>().ReverseMap();
      }
    }
    

    then in you code:

    UserDTO user = Mapper.Map<UserDTO>(context.Users.First(s => s.UserId == 1));
    

    To Map a List:

    List<UserDTO> users = Mapper.Map<IEnumerable<UserDTO>>(context.Users).ToList();
    

    As long as the Name of the Properties are the same they should map.