【问题标题】:Data Mapping an Adjacency List Model with AutoMapper [duplicate]使用 AutoMapper 映射邻接列表模型的数据 [重复]
【发布时间】:2013-01-24 15:21:28
【问题描述】:

所以有一个模型对象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 服务来填充我的模型类。

我想做这样的事情:

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 填充我的树结构?

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 好吧。经过进一步检查,我意识到这个解决方案只有在你从树的顶部开始时才有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2011-08-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    相关资源
    最近更新 更多