【发布时间】:2011-03-05 17:09:15
【问题描述】:
大家好,我使用的是 automapper 版本 1.1.0.188
在我的 AutoMapper.Configure 中,我将实体映射到 DTO,反之亦然,如下所示:
// entity >> DTO
Mapper.CreateMap<MetaTemplate, MetaTemplateDTO>();
Mapper.CreateMap<Person, PersonDTO>();
// DTO >> Entity
Mapper.CreateMap<MetaTemplateDTO, MetaTemplate>();
Mapper.CreateMap<PersonDTO, Person>();
当我执行以下映射(反之亦然)时,一切正常
Mapper.Map<entity, entityDTO>(entity);
Mapper.Map<List<entity>, List<entityDTO>>(entities);
请注意,自动映射器仅适用于 List,而无需我进行任何配置。
我有一个通用容器(本示例已简化):
public class Container<T>
{
public int TotalItems{get;set;}
public IList<T> Items{get;set;}
}
现在,没有任何额外的自动映射配置,当我这样做时:
Mapper.Map<Container<entity>, Container<entityDTO>>(entityContainer);
我得到一个自动映射器异常:
缺少类型映射配置或不支持的映射。异常
但是,如果我在自动映射配置中为特定类型添加这一行,如下所示,那么容器映射将起作用。
Mapper.CreateMap<Container<PersonDTO>, Container<Person>>();
但是,它仅适用于该 Person/PersonDTO 类型。
这是为什么?如何让 automapper 识别 Container 类,因为它识别 List??
我不想再次为每种类型显式配置映射。
酷,干杯
【问题讨论】:
-
我不知道如何使用 AutoMapper 来完成此任务,但您是否尝试过 EmitMapper (emitmapper.codeplex.com)?使用 EmitMapper,如果您将 Container
.Items 的类型更改为 List ,则可以使用 0 配置完成此映射. -
你的意思是问题出在 IList 上?
-
不,我的意思是,只要将 Container.Items 的类型更改为 List
,就可以使用 EmitMapper 进行此映射而无需配置。 -
啊……好吧,很有趣。我认为当前的项目不会发生,但我会看看它,干杯
标签: c# generics .net-3.5 automapper