我正在使用automapper,我想知道当该字段为空时是否可以忽略字段的映射。
这是我的代码:
.ForMember(dest => dest.BusinessGroup_Id,
opt => opt.MapFrom(src => (int)src.BusinessGroup))
src.BusinessGroup type = "enum"
dest.BusinessGroup_Id = int
如果src.BusinessGroup = null,那么它将成为映射的目标。
答案 0 :(得分:26)
我认为NullSubstitute
选项可以解决问题
.ForMember(d => d.BusinessGroup_Id, o => o.MapFrom(s => (int?)s.BusinessGroup));
.ForMember(d => d.BusinessGroup_Id, o => o.NullSubstitute(0));
BTW你可以在映射动作中写下你的条件:
.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;
});