使用AutoMapper数据映射邻接列表模型

时间:2013-02-08 19:11:52

标签: c# automapper adjacency-list data-mapping

所以有一个模型对象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;}
}

此结构由使用Adjacency List Pattern的数据库提供支持。我正在使用带AutoMapper的WCF服务来填充我的Model类。

我想做这样的事情:

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));
  });
}

但显然这会导致无限循环(如果我只映射孩子,它确实有效)。有没有办法使用AutoMapper填充我的树结构?

1 个答案:

答案 0 :(得分:0)

我找到了这个部分解决方案。起初我虽然这是我正在寻找的东西,但经过进一步的检查,它只有在你从树的顶部开始才有效。如果从中间开始,它不会填充父节点。

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;
    }
}