简体   繁体   中英

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 flat 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 do a conversion:

 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 the below is always null instead of having the child list:

rootDto.childs[0].childs

(ie only first level child is mapped correctly)

If I remove the prop.Ignore part I get an assert error that the childs property is not mapped.

What am I doing wrong?

This is old, but came across it looking for something else... You're telling it to ignore the childs field. AutoMapper is doing what it was told to do.

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

You don't have properties in your classes public string Name {get;set;} , you have public Fields, I think that's the problem

also in order to map this classes you only need to create 2 simple maps

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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