首页 > 解决方案 > 如何在 C# Automapper 中忽略空值

问题描述

我在 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

请指教。

标签: c#.net-coreautomapper

解决方案


我认为你必须更新你的ConfigureServices喜欢=>

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 => options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore);Newtonsoft.Json.NullValueHandling.Ignore,它会处理你所要求的。
注意:请检查文档的链接。我相信它会成功的。
关联


推荐阅读