Note that there are some explanatory texts on larger screens.

plurals
  1. POAutomapper throws System.ArgumentException
    text
    copied!<p>I've updated AutoMapper to its version 2 and I've got a lot a problems with it now...</p> <p>I've got a list of <code>ItemToMap</code> and all of these objects have got a reference to the same object <code>Tag</code></p> <p>When I try to map <code>ItemToMap</code> with <code>ItemToMapDto</code>, I've got this error:</p> <blockquote> <p>AutoMapper.AutoMapperMappingException : </p> <p>Mapping types: Tag -> TagDto DAL.Entities.Tag -> DTO.Objects.TagDto</p> <p>Destination path: ItemToMap[][1].Tag.Tag</p> <p>Source value: Entities.Tag ----> System.ArgumentException : An item with the same key has already been added.</p> </blockquote> <p>Here's the mapping:</p> <pre><code>Mapper.CreateMap&lt;ItemToMap, ItemToMapDto&gt;(); Mapper.CreateMap&lt;Tag, TagDto&gt;(); </code></pre> <p>Here's the unit test that highlights my problem:</p> <pre><code>var temp = new List&lt;ItemToMap&gt;(); var tag1 = this.RandomTag; var length = 10; for (int i = 0; i &lt; length; i++) { temp.Add(new ItemToMap() { Tag = tag1, }); } var record = temp.ToArray(); var mapped = Mapper.Map&lt;ItemToMap[], ItemToMapDto[]&gt;(record); </code></pre> <p>What is the solution to have my mapping works? I'm looking for a global solution because the problem is spread all around the code...</p> <p><strong>EDIT 1:</strong></p> <p>The problem comes from the ctor below, if I comment the code of the ctor, everything works fine...</p> <pre><code>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; } } </code></pre> <p><strong>EDIT 2:</strong></p> <p>Automapper is caching <code>ResolutionContext</code> to reuse already set resolvers. In other words, it loops through the mappers and takes the one that return true on the call of <code>IsMatch</code>. To know whether this <code>ResolutionContext</code> is cached, it checks if the destination property is already set and the hash code of the context. Because the destination is set in the Ctor, Automapper considers this is not cached and therefore, it calls the uncached resolver. The latter resolver will cache but it fails because the hash code already exists in the <code>Dictionary</code> used as cache repository</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload