假设我有以下类
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?
答案 0 :(得分:3)
我对你的问题做了一些假设。
Parent
映射到ParentVm
(以及Child
到ChildVm
)。Parent
。ParentId
映射到ChildVm
。ParentId
。如果这两个都是真的,那么以下代码段(来自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
}
输出: