Home > database >  AutoMapper : How to ignore child of child object from mapping using AutoMapper in c#
AutoMapper : How to ignore child of child object from mapping using AutoMapper in c#

Time:10-07

I have below class structure

    public class Parent
    {
        public int ParentID { get; set; }
        public string ParentName { get; set; }
        public Child Child { get; set; }
    }

    public class ParentMap
    {
        public int ParentID { get; set; }
        public string ParentName { get; set; }
        public Child Child { get; set; }
    }

    public class Child
    {
        public int ChildID { get; set; }
        public string ChildName { get; set; }
        public InnerChild InnerChild { get; set; }
    }

    public class InnerChild
    {
        public int InnerChildID { get; set; }
        public string InnerChildName { get; set; }
        public Parent Parent { get; set; }
    }

I want to map Parent class with ParentMap class. After mapping, I need Parent's Child object. But I don't need Parent's Child.InnerChild object(Its ok to set it to null). I've already tried with ForPath() as below. But it will stop mapping entire Child object.

CreateMap<Parent, ParentMap>()
  .ForPath(o => o.Child.InnerChild, opt => opt.Ignore());

Can some one tell me how do I resolve this issue.

CodePudding user response:

This is one quick way to resolve your issue

CreateMap<Parent, ParentMap>()
    .AfterMap((src, dst) =>
    {
        dst.Child.InnerChild = null;
    });
  • Related