So have have an model object TreeNode:

Public Class TreeNode{
  Public int NodeId {get;set;}
  Public String Name {get;set;}
  Public int ParentId {get;set;}
  Public TreeNode Parent {get;set;}
  Public List<TreeNode> Children {get;set;}
}

This structure is powered by a databases using an Adjacency List Pattern. I'm using a WCF service with AutoMapper to populate my Model classes.

I want to do something like this:

public static void ConfigureMappings()
{
  Mapper.CreateMap<TreeNodeDto, Taxonomy>()
  .AfterMap((s, d) =>
  {  
     //WCF service calls to get parent and children
     d.Children =  Mapper.Map<TreeNodeDto[], TreeNode[]>(client.GetTreeChildren(s)).ToList();
     d.Parent = Mapper.Map<TreeNodeDto, TreeNode>(client.GetTreeParent(s));
  });
}

But obviously this causes an infinite loop (it does work if I only map children tho). Is there any way to populate my tree structure using AutoMapper?

有帮助吗?

解决方案

I found this partial solution. At first I though it was what I was looking for but after further inspection it only works if you start at the top of the tree. It doesn't populate the Parent nodes if you start in the middle.

How to assign parent reference to a property in a child with AutoMapper

public static void ConfigureMappings()
{
  Mapper.CreateMap<TreeNodeDto, Taxonomy>()
  .AfterMap((s, d) =>
  {  
     //WCF service calls to get parent and children
     d.Children =  Mapper.Map<TreeNodeDto[], TreeNode[]>(client.GetTreeChildren(s)).ToList();
    foreach( var child in d.Children)
    {
       child.Parent = d;
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top