自动映像和嵌套对象

时间:2017-10-05 16:44:39

标签: c# automapper

假设我有以下类

public class Parent {
    public int ParentId { get; set; }
    public List<Child> Children{get; set; }
    // other properties
}

public class Child {
    public int ChildId { get; set; }
    // other properties
}


public class ParentVm {
    public int ParentId { get; set; }
    public List<ChildVm> Children{get; set; }
    // other properties
}

public class ChildVm {
    public int ParentId { get; set; }
    public int ChildId { get; set; }
    // other properties
}

Parent parent = /*something*/
var parentVm = Mapper.Map<ParentVm>(parent);

ChildVm中,有属性ParentId。如何将该值传播到使用automapper?

1 个答案:

答案 0 :(得分:3)

我对你的问题做了一些假设。

  1. 您正在尝试将Parent映射到ParentVm(以及ChildChildVm)。
  2. 您正在尝试将ParentParentId映射到ChildVmParentId
  3. 如果这两个都是真的,那么以下代码段(来自LINQPad)应该可以帮助您。请注意在第一个AfterMap中使用CreateMap

    void Main()
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Parent, ParentVm>().AfterMap((s, d) =>
            {
                foreach (var child in d.Children)
                {
                    child.ParentId = d.ParentId;
                }
            });
            cfg.CreateMap<Child, ChildVm>();
        });
    
        var mapper = config.CreateMapper();
    
        var parent = new Parent { ParentId = 1, Children = new List<Child>() };
        var child1 = new Child { ChildId = 1 };
        var child2 = new Child { ChildId = 2 };
        parent.Children.Add(child1);
        parent.Children.Add(child2);
    
        var parentVm = mapper.Map<Parent, ParentVm>(parent);
        parentVm.Dump();
    }
    
    public class Parent
    {
        public int ParentId { get; set; }
        public List<Child> Children { get; set; }
        // other properties
    }
    
    public class Child
    {
        public int ChildId { get; set; }
        // other properties
    }
    
    
    public class ParentVm
    {
        public int ParentId { get; set; }
        public List<ChildVm> Children { get; set; }
        // other properties
    }
    
    public class ChildVm
    {
        public int ParentId { get; set; }
        public int ChildId { get; set; }
        // other properties
    }
    

    输出:

    LINQPad Dump Results