我正在使用自动映射器,我想知道当字段为空时是否可以忽略字段的映射。
这是我的代码:
.ForMember(dest => dest.BusinessGroup_Id,
opt => opt.MapFrom(src => (int)src.BusinessGroup))
-
src.BusinessGroup type = "enum"
dest.BusinessGroup_Id = int
目标是忽略 arc.Business Group = null 的映射。
I think NullSubstitute https://github.com/AutoMapper/AutoMapper/wiki/Null-substitution选项就能解决问题
.ForMember(d => d.BusinessGroup_Id, o => o.MapFrom(s => (int?)s.BusinessGroup));
.ForMember(d => d.BusinessGroup_Id, o => o.NullSubstitute(0));
顺便说一句,您可以在映射操作中写入您的条件:
.ForMember(d => d.BusinessGroup_Id,
o => o.MapFrom(s => s.BusinessGroup == null ? 0 : (int)s.BusinessGroup));
UPDATE如果您无法为属性分配一些默认值,则可以忽略它并仅映射非空值:
.ForMember(d => d.BusinessGroup_Id, o => o.Ignore())
.AfterMap((s, d) =>
{
if (s.BusinessGroup != null)
d.BusinessGroup_Id = (int)s.BusinessGroup;
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)