【发布时间】:2012-10-16 07:23:24
【问题描述】:
我已将 AutoMapper 更新到第 2 版,但现在我遇到了很多问题...
我有一个ItemToMap 的列表,所有这些对象都引用了同一个对象Tag
当我尝试将ItemToMap 与ItemToMapDto 映射时,出现此错误:
AutoMapper.AutoMapperMappingException:
映射类型: 标记 -> 标记Dto DAL.Entities.Tag -> DTO.Objects.TagDto
目标路径: ItemToMap[][1].Tag.Tag
来源价值: 实体标签 ----> System.ArgumentException : 已添加具有相同键的项。
这是映射:
Mapper.CreateMap<ItemToMap, ItemToMapDto>();
Mapper.CreateMap<Tag, TagDto>();
这是突出我的问题的单元测试:
var temp = new List<ItemToMap>();
var tag1 = this.RandomTag;
var length = 10;
for (int i = 0; i < length; i++)
{
temp.Add(new ItemToMap()
{
Tag = tag1,
});
}
var record = temp.ToArray();
var mapped = Mapper.Map<ItemToMap[], ItemToMapDto[]>(record);
让我的映射工作的解决方案是什么?我正在寻找一个全球性的解决方案,因为问题遍布整个代码......
编辑 1:
问题来自下面的ctor,如果我评论ctor的代码,一切正常...
public class ItemToMapDto
{
public ItemToMapDto()
{
/* If I comment the line below, all's fine... But it not the behaviour
* I want, I'd like to have a default value for the property...
*/
this.Tag = new TagDto() { Name = this.RandomText };
}
public string Name
{
get;
set;
}
public TagDto Tag
{
get;
set;
}
}
编辑 2:
Automapper 正在缓存 ResolutionContext 以重用已设置的解析器。换句话说,它循环遍历映射器并获取在调用IsMatch 时返回true 的映射器。要知道这个ResolutionContext 是否被缓存,它会检查目标属性是否已经设置以及上下文的哈希码。因为目标是在 Ctor 中设置的,所以 Automapper 认为它没有被缓存,因此它调用未缓存的解析器。后一个解析器会缓存但它失败了,因为哈希码已经存在于用作缓存存储库的Dictionary 中
【问题讨论】:
标签: c# automapper automapper-2