Имам следната структура на класа:
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();
}
}
но не знам как (ако изобщо е възможно) да получа препратка към обекта DstParent, произведен от Mapper.
Някой има ли идея как да направи това или по-скоро трябва да помисля да премахна напълно този дизайн и да се отърва от препратката към родител? Благодаря предварително.