TuomasK
TuomasK

Reputation: 1899

AutoMapper doesn't ignore nested types

I have a situation where AutoMapper doesn't work properly with ignoring members. Here is the class structure and mappings.

public class Class1 {
      public Class2 Class2 { get; set; }
}

public class Class2 {
     public List<Class3> class3List { get; set; }
}

Mapper.CreateMap<Class1, Class1>();
Mapper.CreateMap<Class2, Class2>
    .ForMember(dest => dest.class3List, opt => opt.Ignore());
Mapper.CreateMap<Class3, Class3>();

And when I map Class1 to Class1

Mapper.Map<Class1, Class1>(object1, object2);

In object 2 the class3List is empty, but before the mapping it had items. If I do the mapping like this.

Mapper.CreateMap<Class1, Class1>();
    .ForMember(dest => dest.Class2, opt => opt.Ignore());
Mapper.CreateMap<Class2, Class2>();
Mapper.CreateMap<Class3, Class3>();

It ignores the Class2 property as it should. So how can I ignore class3List and not emptying it, when mapping Class1 to Class1?

Upvotes: 1

Views: 1377

Answers (1)

Dave Walker
Dave Walker

Reputation: 3523

Usually mapping is done from a class of one type to a class of another type. What are you trying to achieve here? A Clone?

Looking at the API I think best to used UseDestinationValue() rather than Ignore. I tested it with your code though and it didnt seem to work still.

 Mapper.CreateMap<ParentFoo, ParentBar>()
     .ForMember(b => b.Child, o => o.UseDestinationValue());

Upvotes: 1

Related Questions