与Automapper的父子关系

时间:2019-02-25 21:19:10

标签: c# automapper

我正在使用Automapper映射我的课程。我的班级A和B都包含父母名单。父类包含子列表。子类具有引用父类的属性。

public class Parent
    {
        public System.Collections.Generic.List<Child> Children { get; set; }

        public class Child
        {
            public Parent MyParent { get; set; }
            public Child() : this(new Parent())
            {
            }
            public Child(Parent parent)
            {
                MyParent = parent;
            }
        }
    }

public class A
{
    public System.Collections.Generic.List<Parent> Parents { get; set; }
    ...
}
public class B
{
    public System.Collections.Generic.List<Parent> Parents { get; set; }
    ...
}

我想使用Automapper将A映射到B。但是我不确定如何配置它,因此当它创建子代时,它将使用新创建的父代。我可以指定在创建子代时应使用的构造函数吗?

CreateMap<A, B>();
CreateMap<Parent, Parent>(); //Configure Automapper to pass new Parent to Child constructor
...

public void TestMethod(){
  Parent parent = new Parent();
  Child child = new Child(parent);
  parent.Children = new List<Child>{child};
  var a = new A(){
      Parents = new List<Parent>{
          parent
      }
  };
  var b = AutoMapper.Mapper.Map<B>(a);
  bool parentIsCorrect = b.Parents[0].Children[0].MyParent == b.Parents[0];
}

我可以通过AfterMap配置在构造函数之外进行操作。

CreateMap<Parent, Parent>()
    .AfterMap((src,dest) => {
        dest.Children?.ForEach(c => c.Parent = dest)
    });

0 个答案:

没有答案
相关问题