AutoMapper を構成して、ソース親オブジェクトの参照を使用して宛先オブジェクトのプロパティを設定する方法を探しています。以下のコードは、私が実現しようとしていることを表しています。データ オブジェクトから親インスタンスと子インスタンスにデータを移動しています。マッピングは、正しいデータを含むリスト コレクションを作成するために正常に機能しますが、親インスタンス参照を割り当てるには 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; }
}
ベストアンサー1
AfterMap を使用します。次のようになります。
Mapper.CreateMap<ParentData, Parent>()
.AfterMap((s,d) => {
foreach(var c in d.Children)
c.Parent = d;
});