When AutoMapper encounters an object that's already been mapped, it seems to use that object again, instead of trying to re-map it. I believe it does this based on .Equals()
.
I have a tree that's being mapped. So, a node with some properties, and children. More than one of the nodes have the same value of .Equals()
, because it's based off an Id property. The children of the nodes are different and I need those re-mapped, but it's using a cached map value.
Is there a way to turn the cached mapping off? All I can think of is implementing a new converter, but that totally defeats the purpose of using AutoMapper.
Here is an example on how to reproduce.
void Main() { var source = new List<Tag> { new Tag { Id = 1, Name = "Tag 1", ChildTags = new List<Tag> { new Tag { Id = 2, Name = "Tag 2", ChildTags = new List<Tag> { new Tag {Id = 3, Name = "Tag 3"}, new Tag {Id = 4, Name = "Tag 4"} } } } }, new Tag { Id = 1, Name = "Tag 1" }, new Tag { Id = 3, Name = "Tag 3", ChildTags = new List<Tag> { new Tag {Id = 4, Name = "Tag 4"} } } }; Mapper.CreateMap<Tag, Tag>(); var results = Mapper.Map<IList<Tag>, IList<Tag>>(source); results.Dump(); } public class Tag { public int Id { get; set; } public string Name { get; set; } public IEnumerable<Tag> ChildTags { get; set; } public override bool Equals(Object obj) { if (obj == null) { return false; } var x = this; var y = (Tag)obj; return x.Id.Equals(y.Id); } public override int GetHashCode() { return Id.GetHashCode(); } }
So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.
Polymorphic element types in collectionsAutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.
AutoMapper will save you writing a LOT of boring mapping code and it will probably spare you from a few nasty bugs as well. The only thing you must be aware of is that the mapping uses convensions and you really want to follow these. As long as you do that, AutoMapper is a great tool!
There is now an option to disable the cache.
Mapper.CreateMap<Tag, Tag>(); var results = Mapper.Map<IList<Tag>, IList<Tag>>(source, opt => opt.DisableCache = true);
I've faced the same issue with the mapper, looking around i found that a solution for it, by adding
Mapper.Reset();
Source blog (corrected URL)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With