如何使用AutoMapper为子项中的属性指定父引用

Six*_*aez 20 automapper

我正在尝试找到一种配置AutoMapper的方法,以通过其源父对象的引用在目标对象中设置属性.下面的代码显示了我想要实现的目标.我正在从数据对象将数据移动到Parent&Child实例中.映射可以正常创建具有正确数据的List集合,但我需要有一个ForEach来分配父实例引用.

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; }
}
Run Code Online (Sandbox Code Playgroud)

Pat*_*ele 52

使用AfterMap.像这样的东西:

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

  • 我也希望有不同的东西.如果您需要处理> 1个子列表,这会非常难看. (4认同)