Core 映射:如何处理引用类型和值类型的 NULL 值
在使用 Core 映射时,可以使用条件语句来判断引用类型和值类型的 null 情况,并进行相应的映射处理。
对于引用类型,可以使用 'IfNotNull' 方法来判断是否为 null,如果不为 null,则进行映射,否则跳过该字段的映射。例如:
CreateMap<Source, Destination>()
.ForMember(dest => dest.ReferenceProperty, opt => opt.Condition(src => src.ReferenceProperty != null));
对于值类型,可以使用 'MapFrom' 方法来指定映射的来源,并使用条件语句判断是否为 null。例如:
CreateMap<Source, Destination>()
.ForMember(dest => dest.ValueProperty, opt => opt.MapFrom(src => src.ValueProperty != null ? src.ValueProperty : defaultValue));
其中,'defaultValue' 是一个默认值,用来替代 null 情况下的映射值。
注意:在进行映射时,需要确保 Source 和 Destination 类型的成员名称和类型匹配,以便进行正确的映射。
原文地址: https://www.cveoy.top/t/topic/qlBZ 著作权归作者所有。请勿转载和采集!