AutoMapping custom Generic Types - How?

吃可爱长大的小学妹 提交于 2019-12-22 12:46:05

问题


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



来源:https://stackoverflow.com/questions/3074617/automapping-custom-generic-types-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!