开发者

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

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; }
}


Use AfterMap. Something like this:

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


Slightly less verbose

CreateMap<Source, Dest>()
  .AfterMap((_, dest) => dest.Children.ForEach(x => x.Parent = dest))

AfterMap

Execute a custom function to the source and/or destination types after member mapping

For completeness, this sort of thing should not really be a concern of automapper, as it leads to overly abstracted side effects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜