Dmitry Koshevoy
Dmitry Koshevoy

Reputation: 331

Automapper doesn't ignore property for descendants

First I'm using automapper 4.2.1. I have a class that represents tree view node. For example this class has three properties and one method:

class A
{
     public string Name{get; set;}
     public bool IsExpanded{get; set;}
     public ObservableCollection<A> Children {get; set;}

     public void UpdateCurrenNode(A object)
     {
        Mapper.Map(object, this);
     }
}

As you can see I have a method that helps me to update current node and its descendants with given object. But I want to ignore property IsExanded. So here is my Map:

CreateMap<A, A>().ForMember(dest => dest.IsExpanded, opts => opts.Ignore());

But after mapping property IsExpanded is ignored only for root object, but it doesn't ignored for descendants. Where am I wrong?

Thanks! Regards, Dmitry

Upvotes: 2

Views: 919

Answers (1)

omerts
omerts

Reputation: 8848

Please try:

CreateMap<A, A>().ForMember(dest => dest.IsExpanded, opts => opts.Ignore())
                 .ForMember(dest => dest.Children, 
                            opt => opt.MapFrom(src => 
                                               src.Children.Select(Mapper.Map<A, A>).ToList()));

For example:

Class A

public class A
{
    private static MapperConfiguration config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<A, A>().ForMember(dest => dest.IsExpanded, opts => opts.Ignore())
                             .ForMember(dest => dest.Children, 
                                        opt => opt.MapFrom(src => src.Children.Select(Mapper.Map<A, A>).ToList()));
    });

    private static IMapper mapper = config.CreateMapper();

    public string Name{get; set;}
    public bool IsExpanded{get; set;}
    public ObservableCollection<A> Children {get; set;}

    public void UpdateCurrenNode(A obj)
    {
       mapper.Map(obj, this);
    }
}

Program

var test1 = new A()
{
    IsExpanded = true,
    Name = "Test1",
    Children = new ObservableCollection<A>()
};

var test2 = new A()
{
    IsExpanded = true,
    Name = "Test2",
    Children = new ObservableCollection<A>()
};

var test3 = new A()
{
    IsExpanded = true,
    Name = "Test3",
    Children = new ObservableCollection<A>()
};

var test = new A()
{
    IsExpanded = true,
    Name = "Test",
    Children = new ObservableCollection<A>() {test1, test2, test3}
};

var clone = new A()
{
    Children = new ObservableCollection<A>()
};

clone.UpdateCurrenNode(test);

Produces: enter image description here


UPDATE

The above example, is also working fine with your original config:

cfg.CreateMap<A, A>().ForMember(dest => dest.IsExpanded, opts => opts.Ignore());

Upvotes: 1

Related Questions