AutoMapper doesn't ignore nested types

﹥>﹥吖頭↗ 提交于 2019-12-11 07:03:36

问题


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?


回答1:


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());


来源:https://stackoverflow.com/questions/7188952/automapper-doesnt-ignore-nested-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!