使用AutoMapper在构造函数中注入父类映射子类我有如下类结构:classSrcChild{publicboolSomeProperty{get;放;}}classSrcParent{publicIEnumerableChildren{get;放;所以SrcParent有一个SrcChild对象的集合。现在我想将SrcParent的一个实例映射到DstParent。这是目标类:classDstChild{publicboolSomeProperty{get;放;}publicDstChild(DstParentparent){if(parent==null)thrownewArgumentNullException();}}classDstParent{publicIEnumerableChildren{get;放;DstParent有一组DstChild对象,这些对象使用构造函数注入来保持对其父对象的引用。使用AutoMapper,我尝试了以下操作:);映射器.CreateMap();/*有两个孩子的源父对象*/varsrcParent=newSrcParent{Children=new[]{newSrcChild(),newSrcChild()}};/*抛出异常*/vardstParent=Mapper.Map(srcParent);控制台.ReadKey();这里的主要部分是AutoMapper配置,我试图从映射上下文中提取对生成的DstParent的引用。这不起作用((DstParent)resolutionContext.Parent.DestinationValue为空),但也许我在这里完全遗漏了一点?我的另一个想法是使用函数来创建子值,如下所示:列表();//result.Add(newDstChild(dstParent));返回结果;}staticvoidMain(string[]args){/*映射配置*/Mapper.CreateMap();映射器.CreateMap()。ForMember(dst=>dst.Children,opt=>opt.MapFrom(src=>MakeChildren(src/*,这里如何获取目的地的引用?*/)));/*有两个孩子的源父对象*/varsrcParent=newSrcParent{Children=new[]{newSrcChild(),newSrcChild()}};vardstParent=Mapper.Map(srcParent);控制台.ReadKey();但是我不知道如何(如果可能的话)引用Mapper生成的DstParent对象。有谁知道如何做到这一点,或者我应该考虑完全放弃这个设计并摆脱父参考?提前致谢。好吧,我找到的解决方案并不漂亮,但它有效:foreach(srcChildren中的SrcChild子对象){vardstChild=newDstChild(dstParent);Mapper.Map(child,dstChild);dstChildren.Add(dstChild);}返回dstChildren;}staticvoidMain(string[]args){Mapper.CreateMap();Mapper.CreateMap()/*创建DstParent时忽略Children属性*/.ForMember(dst=>dst.Children,opt=>opt.Ignore())/*映射完成后,填充Children属性*/.AfterMap((srcParent,dstParent)=>{dstParent.Children=MakeChildren(srcParent.Children,dstParent);});varsource=newSrcParent{Children=new[]{newSrcChild(){SomeProperty=true},newSrcChild(){SomeProperty=false}}};vardestination=Mapper.Map(source);控制台.ReadKey();}}目标初始化子,AutoMapper正确分配SomeProperty。如果您找到更好看的解决方案,请告诉我。以上就是C#学习教程:使用AutoMapper在构造函数中注入父类映射子类共享的所有内容。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文来自网络收集,不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
