繁体   English   中英

自动映射 - 忽略条件映射

[英]Automapper - Ignore mapping with condition

我正在使用automapper,我想知道当该字段为空时是否可以忽略字段的映射。

那是我的代码:

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

目标是,如果src.BusinessGroup = null,那就是映射。

我认为NullSubstitute选项可以解决问题

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

更新如果您不能为您的属性分配一些默认值,您可以忽略它并仅映射非空值:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM