【问题标题】:Automapper throws System.ArgumentExceptionAutomapper 抛出 System.ArgumentException
【发布时间】:2012-10-16 07:23:24
【问题描述】:

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

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

当我尝试将ItemToMapItemToMapDto 映射时,出现此错误:

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


    【解决方案1】:

    您必须注册 DAL.Entities.TagDTO.Objects.TagDto,尽管您在 Tag 和 TagDto 上具有相同的属性名称

    我猜你没有映射Tag 类中的一些属性。如果是这样,请使用Ignore

    Mapper.CreateMap<Tag, TagDto>().ForMember(x => x.value, opt => opt.Ignore());
    

    看看Here & Here & Here

    【讨论】:

    • 这不是问题。我为所有东西创建了一张地图。我更新了我的帖子以显示它。
    • 属性不是问题。所有stringstring.IsNullOrEmpty 总是假的。
    • 问题出在 Automapper 的 ResolutionContext 的缓存策略上。有关详细信息,请参阅我的编辑 2
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多