首页 > 解决方案 > 从集合中删除空值

问题描述

我们通常有这样的用例,即我们有一个在 ( new SomeType[]{null}) 中包含一个空元素的集合。现在我们有一个扩展方法可以删除这些空元素,但显然我们必须为我们想要映射的每个集合配置它。

是否有一些通用的方法来告诉 automapper 从集合中删除空值,无论是全局还是每个配置文件?

标签: c#automapper

解决方案


AotoMapper 提供条件映射

举个例子,

CreateMap<MyClassDTO, MyClass>()
     .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

在全局级别开启(未测试)

Mapper.Initialize(cfg =>
{
    cfg.ForAllMaps((typeMap, map) =>
        map.ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
}

推荐阅读