【问题标题】:How to ignore null values in C# Automapper如何在 C# Automapper 中忽略空值
【发布时间】:2021-01-27 04:43:03
【问题描述】:

我在 C# 中使用 Automapper。

目前我正在尝试使用以下代码进行映射。

CreateMap<Student, StudentDto>()
.ForMember(dest => dest.FeeType, opt =>
{
 opt.PreCondition(src => (src.Key == "Paid"));
 opt.MapFrom(src => src.Value);
});

我只想在密钥 == 付费时进行映射,否则它不应该映射。但是在这种情况下,它只是传递 null。

假设集合有 100 条记录,并且只有 1 条符合条件,其他 99 条记录作为 NULL 传递。

编辑 -- 我正在使用 Azure Function Apps,我的 Automapper 版本是 10.0.0

请指教。

【问题讨论】:

  • 答案是 Automapper 6,我用的是 10。我试过 ForAllMaps((obj, cnfg) => cnfg.ForAllMembers(opts => opts.Condition((src, dest, srcMember) = > srcMember != null)));但它没有用。

标签: c# .net-core automapper


【解决方案1】:

我认为你必须更新你的ConfigureServiceslike=>

public void ConfigureServices(IServiceCollection services) {  
    // Auto Mapper Configurations  
    var mappingConfig = new MapperConfiguration(mc => {  
        mc.AddProfile(new MappingProfile());  
    });  
    IMapper mapper = mappingConfig.CreateMapper();  
    services.AddSingleton(mapper); 
    //This line should be updated
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(options => options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore);  
}  

.AddJsonOptions(options =&gt; options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore); ofNewtonsoft.Json.NullValueHandling.Ignore,它会处理你所要求的。
注意:请查看文档链接。我相信它会成功的。
LINK

【讨论】:

  • 对不起,我之前没有提到,但我使用的是 Azure Function 应用程序。如果可能的话,我正在寻找可以在我的 Automapper 配置文件本身中配置的东西。
猜你喜欢
  • 2023-01-26
  • 2022-06-25
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
  • 1970-01-01
相关资源
最近更新 更多