Polymorphism with AutoMapper

I have these business classes:

class BaseNode { public string name; } class CompositeNode : BaseNode { public List<BaseNode> childs = new List<BaseNode>(); } 

And this apartment is dto:

 class NodeDto { public string name; public List<NodeDto> childs; } 

(note how all derived types are represented by one dto class)

I use auto mapper to convert:

  Mapper.CreateMap<BaseNode, NodeDto>() .Include<CompositeNode, NodeDto>() .ForMember(s => s.childs, prop => prop.Ignore()); Mapper.CreateMap<CompositeNode, NodeDto>(); Mapper.AssertConfigurationIsValid(); var root = new CompositeNode() { name = "root" }; var child = new CompositeNode {name = "child"}; var child2 = new CompositeNode { name = "child2" }; root.childs.Add(child); child.childs.Add(child2); var rootDto = Mapper.Map<CompositeNode, NodeDto>(root); 

However, below is always null instead of a list of children:

 rootDto.childs[0].childs 

(i.e. only the first level child is displayed correctly)

If I delete the prop.Ignore part, I get an assert error that the childs property is not displayed.

What am I doing wrong?

+4
source share
2 answers

It is old, but stumbled upon it, looking for something else ... You tell it to ignore the childs field. AutoMapper does what he was told.

 .ForMember(s => s.childs, prop => prop.Ignore()); 
0
source

You have no properties in your classes public string Name {get;set;} , you have open fields, I think the problem

also to display these classes you only need to create 2 simple maps

 Mapper.CreateMap<CompositeNode, NodeDto>(); Mapper.CreateMap<BaseNode, NodeDto>() .ForMember(s => s.childs, prop => prop.Ignore());; 
-2
source

All Articles