在Automapper 6中进行映射时,如何忽略所有源成员的空值? [英] How to ignore null values for all source members during mapping in Automapper 6?

查看:370
本文介绍了在Automapper 6中进行映射时,如何忽略所有源成员的空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我到处都在寻找:stackoverflow,自动映射器文档,互联网,甚至找不到关于这方面的任何信息,即使这似乎是一个非常普遍的问题.

I've been looking everywhere: stackoverflow, automapper documentation, internets and just couldn't find any info on this one, even tho this seems to be a very common problem.

我的映射:

CreateMap<StatusLevelDTO, StatusLevel>()
            .ForAllMembers(opt => opt.Condition(src => src != null));

这不起作用,因为src表示源对象(StatusLevelDTO),而不是源属性(我认为).

This doesn't work because src represents source object (StatusLevelDTO), not a source property (I think).

更具体地说,如果我将ObjectA映射到ObjectB,则ObjectA.SomeValue为null,ObjectB.SomeValue为2,我希望目标对象保留其值(2).

To be more specific, If I map ObjectA to ObjectB, ObjectA.SomeValue is null and ObjectB.SomeValue is 2, I want the destination object to keep its value (2).

我已经看到以下问题:自动映射器使用自定义解析器跳过空值并尝试了前两个答案,但对于版本6,它们似乎都已过时.

I've seen this question: Automapper skip null values with custom resolver and tried the first two answers but they both seem to be outdated for version 6.

在Automapper 6中有什么方法可以做到这一点?我使用的是6.0.2.

Is there any way to make this happen in Automapper 6? I am using 6.0.2 to be exact.

推荐答案

方法 Condition 现在有五个重载,其中一个重载类型为

Method Condition now has five overloads, one of which accepts predicate of type

Func<TSource, TDestination, TMember, bool>

此TMember参数是源成员.因此,您可以检查源成员是否为空:

this TMember parameter is the source member. So you can check source member for null:

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

这篇关于在Automapper 6中进行映射时,如何忽略所有源成员的空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆