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:

1
2
3
4
5
6
7
8
9
10
public class PersonModel
{
    public Guid Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public ICollection<Hobby> Hobbies { get; set; }
}

The Hobby class looks like this:

1
2
3
4
5
6
7
8
public class Hobby
{
    public Guid Id { get; set; }

    public Guid PersonId { get; set; }

    public string Name { get; set; }
}

And the destination class looks like this:

1
2
3
4
5
6
7
8
9
10
public class PersonEntity
{
    public Guid Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public ICollection<Hobby> Hobbies { get; set; }
}

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:

1
2
3
4
5
6
7
8
    CreateMap<PersonModel, PersonEntity>()
        .AfterMap((source, destination) =>
        {
            foreach(Hobby hobby in destination.Hobbies)
            {
                hobby.PersonId = source.Id;
            }
        });

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.

comments powered by Disqus