AutoMapping custom Generic Types - How?

2019-05-20 12:46发布

问题:

hey guys, I'm using automapper version 1.1.0.188

In my AutoMapper.Configure I'm mapping Entities to DTOs and vice versa, like so:

// entity >> DTO
Mapper.CreateMap<MetaTemplate, MetaTemplateDTO>();
Mapper.CreateMap<Person, PersonDTO>();     

// DTO >> Entity
Mapper.CreateMap<MetaTemplateDTO, MetaTemplate>();
Mapper.CreateMap<PersonDTO, Person>();

When I do the below mappings (and vice versa) everything works fine

Mapper.Map<entity, entityDTO>(entity);

Mapper.Map<List<entity>, List<entityDTO>>(entities);

Note above that automapper just works with List<> without me having to configure anything.

I have a Generic Container (simplified for this example):

public class Container<T>
{
    public int TotalItems{get;set;}
    public IList<T> Items{get;set;}
}

Now, without any extra automapping config, when I do:

Mapper.Map<Container<entity>, Container<entityDTO>>(entityContainer);

I get an automapper exception:

Missing type map configuration or unsupported mapping.Exception

However, if I add this line in the automap configure for a specific type, as below, then the Container mapping works.

Mapper.CreateMap<Container<PersonDTO>, Container<Person>>();

However, it will ONLY work for that Person/PersonDTO type.

Why is this? How can I make automapper recognize the Container class as it recognizes List<>??

I don't want to explicitly configure mappings for every type AGAIN.

cool, cheers

回答1:

If your generic container class behaves like a list of objects then you may be best off implementing the IEnumerable interface. Then the automapper should be able to iterate through the objects and map them accordingly.



回答2:

The answer is that Automapper just doesn't deal with unsupported types, even if the Type you're using is a container of supported types.

The solution was to map the object manually