如何使用AutoMapper将父级引用分配给子级中的属性 [英] How to assign parent reference to a property in a child with AutoMapper
本文介绍了如何使用AutoMapper将父级引用分配给子级中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到一种配置AutoMapper的方法,以使用其源父对象的引用在目标对象中设置属性.下面的代码显示了我正在尝试实现的目标.我正在将数据移入父母与父母"数据对象的子实例.映射可以很好地创建具有正确数据的List集合,但是我需要有一个ForEach来分配父实例引用.
I'm trying to find a way of configuring AutoMapper to set a property in a destination object with a reference of its source parent object. The code below shows what I'm trying to achieve. I'm moving data into the Parent & Child instances from the data objects. The mapping works fine to create the List collection with correct data but I need to have a ForEach to assign the parent instance reference.
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; }
}
推荐答案
使用AfterMap.像这样:
Use AfterMap. Something like this:
Mapper.CreateMap<ParentData, Parent>()
.AfterMap((s,d) => {
foreach(var c in d.Children)
c.Parent = d;
});
这篇关于如何使用AutoMapper将父级引用分配给子级中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文