Reputation: 4227
I would like to map a Dto to an Entity, and store the array index of the Dto into a property on the Entity.
e.g (pseudo):
class Dto {}
class Entity{ int Index; }
// perform mapping from collection of Dto, to collection of Entity
Map<Entity>(new Dto[]{ new Dto(), new Dto(), new Dto() };
// maps to
Entity[]{
Entity{ Index = 0 },
Entity{ Index = 1 },
Entity{ Index = 2 }
}
Sure I can do this manually, however, I already have AutoMapper in my architecture, so it makes sense to configure a mapping for it.
I cannot find a way to do this. I found this thread: https://github.com/AutoMapper/AutoMapper/issues/1238
Which alludes to using a resolver, however, resolvers no longer have access to the resolution hierarchy/stack. I believe this may have been changed for performance reasons, since the comment above was written.
It seems to me, I should be able to easily get access to the 'root' source object (the object/collection passed in to the Map<>(source) method - and having such access would make it trivial to solve this - but I cannot find it.
Any pointers?
Thanks,
Upvotes: 3
Views: 906
Reputation: 9516
Here is how you could achieve it using AfterMap:
Mapper.CreateMap<SourceDto, Destination>()
.AfterMap((_, dest) =>
{
int id = 0;
foreach (var entity in dest.Entities)
{
entity.Index = id++;
}
});
Upvotes: 1