使用AutoMapper在构造函数中注入父类映射子类

我有以下类结构:

class SrcChild { public bool SomeProperty { get; set; } } class SrcParent { public IEnumerable Children { get; set; } } 

所以SrcParent有一个SrcChild对象的集合。

现在我想将SrcParent的实例映射到DstParent。 以下是目标类:

 class DstChild { public bool SomeProperty { get; set; } public DstChild(DstParent parent) { if (parent == null) throw new ArgumentNullException(); } } class DstParent { public IEnumerable Children { get; set; } } 

DstParent有一个DstChild对象的集合,它使用构造函数注入来保持对其父对象的引用。

使用AutoMapper,我尝试了以下方法:

 class Program { static void Main(string[] args) { /* mapping configuration */ Mapper.CreateMap() .ConstructUsing( resolutionContext => new DstChild((DstParent)resolutionContext.Parent.DestinationValue)); Mapper.CreateMap(); /* source parent object with two children */ var srcParent = new SrcParent { Children = new[] { new SrcChild(), new SrcChild() } }; /* throws an exception */ var dstParent = Mapper.Map(srcParent); Console.ReadKey(); } } 

这里的主要部分是AutoMapper配置,我试图从映射上下文中提取对生成的DstParent的引用。 这不起作用((DstParent)resolutionContext.Parent.DestinationValue为null),但也许我在这里完全错过了一个观点?

我的另一个想法是使用函数来创建子值,如下所示:

 class Program { /* Should produce value for DstParent.Children */ private static IEnumerable MakeChildren(SrcParent src /*, DstParent dstParent */) { var result = new List(); // result.Add(new DstChild(dstParent)); return result; } static void Main(string[] args) { /* mapping configuration */ Mapper.CreateMap(); Mapper.CreateMap() .ForMember(dst => dst.Children, opt => opt.MapFrom(src => MakeChildren(src /*, How to obtain a reference to the destination here? */))); /* source parent object with two children */ var srcParent = new SrcParent { Children = new[] { new SrcChild(), new SrcChild() } }; var dstParent = Mapper.Map(srcParent); Console.ReadKey(); } } 

但我不知道如何(如果可能的话)可以引用Mapper生成的DstParent对象。

有没有人知道如何做到这一点,或者我是否应该考虑完全放弃这个设计并摆脱父参考? 提前致谢。

好吧,我找到的解决方案并不漂亮,但它有效:

 class Program { static IEnumerable MakeChildren(IEnumerable srcChildren, DstParent dstParent) { var dstChildren = new List(); foreach (SrcChild child in srcChildren) { var dstChild = new DstChild(dstParent); Mapper.Map(child, dstChild); dstChildren.Add(dstChild); } return dstChildren; } static void Main(string[] args) { Mapper.CreateMap(); Mapper.CreateMap() /* Ignore Children property when creating DstParent*/ .ForMember(dst => dst.Children, opt => opt.Ignore()) /* After mapping is complete, populate the Children property */ .AfterMap((srcParent, dstParent) => { dstParent.Children = MakeChildren(srcParent.Children, dstParent); }); var source = new SrcParent { Children = new[] { new SrcChild() {SomeProperty = true}, new SrcChild() {SomeProperty = false} } }; var destination = Mapper.Map(source); Console.ReadKey(); } } 

目标已初始化子项,AutoMapper正确分配了SomeProperty。 如果您找到更好看的解决方案,请告诉我。