我有以下的类结构:
class SrcChild
{
public bool SomeProperty { get; set; }
}
class SrcParent
{
public IEnumerable<SrcChild> 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<DstChild> Children { get; set; }
}
DstParent有一个DstChild对象的集合,并使用构造函数注入来保持对其父对象的引用。
使用AutoMapper,我尝试了以下方法:
class Program
{
static void Main(string[] args)
{
/* mapping configuration */
Mapper.CreateMap<SrcChild, DstChild>()
.ConstructUsing(
resolutionContext => new DstChild((DstParent)resolutionContext.Parent.DestinationValue));
Mapper.CreateMap<SrcParent, DstParent>();
/* source parent object with two children */
var srcParent = new SrcParent
{
Children = new[] { new SrcChild(), new SrcChild() }
};
/* throws an exception */
var dstParent = Mapper.Map<DstParent>(srcParent);
Console.ReadKey();
}
}
这里的主要部分是AutoMapper配置,我试图从映射上下文中提取对生成的DstParent的引用。但这并不起作用((DstParent)resolutionContext.Parent.DestinationValue为null),但也许我完全错过了重点?
我另一个想法是使用一个函数来创建子值,类似于这样:
class Program
{
/* Should produce value for DstParent.Children */
private static IEnumerable<DstChild> MakeChildren(SrcParent src /*, DstParent dstParent */)
{
var result = new List<DstChild>();
// result.Add(new DstChild(dstParent));
return result;
}
static void Main(string[] args)
{
/* mapping configuration */
Mapper.CreateMap<SrcChild, DstChild>();
Mapper.CreateMap<SrcParent, DstParent>()
.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<DstParent>(srcParent);
Console.ReadKey();
}
}
但我不知道如何(如果有可能的话)获取由Mapper生成的DstParent对象的引用。
有人有想法如何做到这一点,还是应该考虑放弃这个设计,摆脱父引用?提前致谢。