简体   繁体   English

Automapper 错误地填充父/子结构

[英]Automapper incorrectly populating parent/child structure

I have the following entity classes, which are mapped from virtually identical view model classes:我有以下实体类,它们是从几乎相同的视图 model 类映射的:

public class Node
{
    public IList<Node> Children { get; set; }
    public Node Parent { get; set; }
    public string Text { get; set; }
}

public class Tree
{
    public Node Root { get; set; }
}

Using the following view model structure使用如下视图model结构

Tree 
    -> Root
        -> Children { node1, node2 }

Once the view model is mapped to the entity, the first child node, of the root node, is the root node and, as a result, I'm getting an infinite loop when I traverse the entity object structure.一旦视图 model 映射到实体,根节点的第一个子节点就是根节点,因此,当我遍历实体 object 结构时,我得到一个无限循环。

Anybody have an idea why this is happening and how to resolve it?任何人都知道为什么会发生这种情况以及如何解决它?

Many thanks非常感谢

Steve史蒂夫

Mapper.CreateMap<NodeViewModel, Node>()
    .ForMember(dto => dto.Children, 
               opt => opt.MapFrom(src => src.Children.Select(nodevm => Mapper.Map<NodeViewModel, Node>(nodevm)).ToList()))
    .ForMember(dto => dto.Parent,
               opt => opt.MapFrom(src => Mapper.Map<NodeViewModel, Node>(src.Parent)))
    .ForMember(dto => dto.Text,
               opt => opt.MapFrom(src => src.Text));

Something like that schould work as the AutoMapper Configuration.类似的东西应该作为 AutoMapper 配置工作。

PS: I did not try it by now, but as I use the AutoMapper very often I think it should work. PS:我现在还没有尝试过,但由于我经常使用 AutoMapper,我认为它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM