简体   繁体   English

如何忽略 C# Automapper 中的 null 值

[英]How to ignore null values in C# Automapper

I am using Automapper in C#.我在 C# 中使用 Automapper。

Currently I am trying to map using below code.目前我正在尝试使用以下代码 map。

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

I want to map only if the key == Paid else it should not map.我想 map 只有在密钥 == 付费的情况下,否则它不应该是 map。 However in this case, it is just passing null.但是在这种情况下,它只是通过 null。

So lets say if the collection has 100 records and only 1 matches the condition other 99 records are passed as NULL.因此,假设集合有 100 条记录并且只有 1 条符合条件,其他 99 条记录作为 NULL 传递。

Edit -- I am using Azure Function Apps and my Automapper version is 10.0.0编辑——我正在使用 Azure Function 应用程序,我的 Automapper 版本是 10.0.0

Please advise.请指教。

I think you have to update your ConfigureServices like=>我认为您必须像 => 一样更新您的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); of Newtonsoft.Json.NullValueHandling.Ignore , It will handle what you ask for. Newtonsoft.Json.NullValueHandling.Ignore ,它将处理您的要求。
Note: Please check the link of a documentation.注意:请检查文档的链接。 I believe it will do the trick.我相信它会成功的。
LINK 关联

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

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