How to assign parent reference to a property in a child with AutoMapper

Sixto Saez picture Sixto Saez · Dec 7, 2010 · Viewed 7.9k times · Source

I'm trying to find a way of configuring AutoMapper to set a property in a destination object with a reference of its source parent object. The code below shows what I'm trying to achieve. I'm moving data into the Parent & Child instances from the data objects. The mapping works fine to create the List collection with correct data but I need to have a ForEach to assign the parent instance reference.

public class ParentChildMapper
{
    public void MapData(ParentData parentData)
    {
        Mapper.CreateMap<ParentData, Parent>();
        Mapper.CreateMap<ChildData, Child>();

        //Populates both the Parent & List of Child objects:
        var parent = Mapper.Map<ParentData, Parent>(parentData);

        //Is there a way of doing this in AutoMapper?
        foreach (var child in parent.Children)
        {
            child.Parent = parent;
        }

        //do other stuff with parent
    }
}

public class Parent
{
    public virtual string FamilyName { get; set; }

    public virtual IList<Child> Children { get; set; }
}

public class Child
{
    public virtual string FirstName { get; set; }

    public virtual Parent Parent { get; set; }
}

public class ParentData
{
    public string FamilyName { get; set; }

    public List<Child> Children { get; set; }
}

public class ChildData
{
    public string FirstName { get; set; }
}

Answer

PatrickSteele picture PatrickSteele · Dec 7, 2010

Use AfterMap. Something like this:

Mapper.CreateMap<ParentData, Parent>()
    .AfterMap((s,d) => {
        foreach(var c in d.Children)
            c.Parent = d;
        });