【问题标题】:How to assign parent reference to a property in a child with AutoMapper如何使用 AutoMapper 将父引用分配给子属性
【发布时间】:2011-05-21 14:43:51
【问题描述】:

我正在尝试找到一种配置 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; }
}

【问题讨论】:

    标签: automapper


    【解决方案1】:

    使用 AfterMap。像这样的:

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

    【讨论】:

    • 我希望完全避免使用循环,但您的回答似乎是唯一的选择。像: .ForMember(dest => dest.Parent, opt => opt.MapFrom(src => src)) 是我正在寻找的东西,但它不起作用。谢谢!
    • 我也希望有一些不同的东西。如果您有 > 1 个需要处理的子列表,这会变得非常难看。
    • 我知道这是一个古老的问题和答案,但你可以使用一些(更多)Linq stackoverflow.com/questions/398871/…
    【解决方案2】:

    略显冗长

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

    AfterMap

    在之后对源和/或目标类型执行自定义函数 成员映射

    为了完整起见,这类事情不应该是 automapper 真正关心的问题,因为它会导致过度抽象的副作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      • 2013-07-07
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多