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:

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:

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:

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:

    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