AutoMapper Ignore on child collection property

橙三吉。 提交于 2019-12-05 20:02:30

There are several bugs in AutoMapper 4.1.1.

First is about UseDestinationValue: https://github.com/AutoMapper/AutoMapper/issues/568

Second is about nested collections: https://github.com/AutoMapper/AutoMapper/issues/934

Horrifying! The workaround is to map your B instances directly:

Mapper.CreateMap<A, A>()
    .ForMember(dest => dest.Id, opt => opt.Ignore())
    .ForMember(dest => dest.Children, opt => opt.Ignore());

Mapper.CreateMap<B, B>()
    .ForMember(dest => dest.Id, opt => opt.Condition((ResolutionContext src) => false));

and add additional mapping calls:

Mapper.Map(src, dest);
Mapper.Map(src.Children.First(), dest.Children.First()); //example!!!

You may call Mapper.Map in cycle:

for (int i = 0; i < src.Children.Count; i++)
{
    var srcChild = src.Children[i];
    var destChild = dest.Children[i];

    Mapper.Map(srcChild, destChild);
}

This will make things work right.

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