c# - 如何在 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
请指教。
解决方案
我认为你必须更新你的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
,它会处理你所要求的。
注意:请检查文档的链接。我相信它会成功的。
关联
推荐阅读
- python - 在 fastapi python 中使 Depends 成为可选
- r - 尝试将大量科学摘要识别为由 R 中的关键字识别的组
- xamarin - DynamicResource 不适用于 Xamarin 中的自定义类型属性
- reactjs - 如何使用 BrowserRouter 外部的持久标头链接到组件?
- java - 无法在 Java 中显示像 ć 这样的特殊字符
- javascript - 带有抽签动画的视差滚动
- text - 如何在 SwiftUI Text 中使用自定义字体使我的文本变为粗体?
- javascript - 如何在 axios 请愿书之前显示一个变量
- laravel - 我无法在 Laravel 中迁移数据库。它说 SQLSTATE[HY000] [2002] 操作超时
- npm - Bootstrap 5 的 Webpack 慢速构建