Automapper - Ignore mapping with condition

白昼怎懂夜的黑 提交于 2019-12-06 18:36:20

问题


I'm using automapper and I would like to know if it's possible to ignore a mapping of a field when that's null.

That's my code:

.ForMember(dest => dest.BusinessGroup_Id, 
           opt => opt.MapFrom(src => (int)src.BusinessGroup))
  • src.BusinessGroup type = "enum"
  • dest.BusinessGroup_Id = int

The objective it's to ingore that Mapping if src.BusinessGroup = null.


回答1:


I think NullSubstitute option will do the trick

.ForMember(d => d.BusinessGroup_Id, o => o.MapFrom(s => (int?)s.BusinessGroup));
.ForMember(d => d.BusinessGroup_Id, o => o.NullSubstitute(0));

BTW you can write your conditions in mapping action:

.ForMember(d => d.BusinessGroup_Id,
           o => o.MapFrom(s => s.BusinessGroup == null ? 0 : (int)s.BusinessGroup));   

UPDATE if you cannot assign some default value to your property, you can just ignore it and map only not nulls:

.ForMember(d => d.BusinessGroup_Id, o => o.Ignore())
.AfterMap((s, d) =>
    {
        if (s.BusinessGroup != null)
            d.BusinessGroup_Id = (int)s.BusinessGroup;
    });


来源:https://stackoverflow.com/questions/13194072/automapper-ignore-mapping-with-condition

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