【发布时间】: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