Skip to main content
 首页 » 编程设计

c#之Automapper 抛出 System.ArgumentException

2024年02月20日26duanxz

我已经将 AutoMapper 更新到第 2 版,但现在我遇到了很多问题...

我有一个 ItemToMap 列表,所有这些对象都引用了同一个对象 Tag

当我尝试将 ItemToMap 映射到 ItemToMapDto 时,出现此错误:

AutoMapper.AutoMapperMappingException :

Mapping types: Tag -> TagDto DAL.Entities.Tag -> DTO.Objects.TagDto

Destination path: ItemToMap[][1].Tag.Tag

Source value: Entities.Tag ----> System.ArgumentException : An item with the same key has already been added.

这是映射:

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); 

让我的 map 工作的解决方案是什么?我正在寻找一个全局解决方案,因为问题遍布整个代码...

编辑 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 中

请您参考如下方法:

这是一个错误。修复将在 2.2.1 版本中