且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Automapper - 忽略与条件映射

更新时间:2022-04-30 08:38:52

我觉得 NullSubstitute 选项就可以了。

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,你可以写你的条件映射动作:

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