簡體   English   中英

如何忽略 C# Automapper 中的 null 值

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

我在 C# 中使用 Automapper。

目前我正在嘗試使用以下代碼 map。

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

我想 map 只有在密鑰 == 付費的情況下,否則它不應該是 map。 但是在這種情況下,它只是通過 null。

因此,假設集合有 100 條記錄並且只有 1 條符合條件,其他 99 條記錄作為 NULL 傳遞。

編輯——我正在使用 Azure Function 應用程序,我的 Automapper 版本是 10.0.0

請指教。

我認為您必須像 => 一樣更新您的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 ,它將處理您的要求。
注意:請檢查文檔的鏈接。 我相信它會成功的。
關聯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM