How to map a property of a parent object to a property inside a list of objects with AutoMapper
Mapping objects with AutoMapper can save you a lot of time and repeated code. However, some mappings are more tricky than others. Consider the example where we want to map two lists of objects and moreover, a specific property of each of these list-objects should contain the value of a property from a parent object.
Let us see this scenario with a concrete example:
Our source class looks like this:
The Hobby class looks like this:
And the destination class looks like this:
You can see that we need to write the PersonModel.Id on the Hobby.PersonId property of every Hobby object while we are mapping from PersonModel to PersonEntity. We will have to write the following mapping:
That’s it. You will have to use the AfterMap()
method for iterating over the objects in the list and assigning to a property of them the value of a parent (source) property. Since the name of both collections is the same, we will not have to add this mapping explicitly.