AutoMapper:如果source == null,则创建目标类型的实例 [英] AutoMapper: create instance of destination type if source == null
问题描述
如果源对象为null,是否可以将AutoMapper配置为返回目标类型的新实例?
Is it possible to configure AutoMapper to return a new instance of the destination type if the source object is null?
Source source = null;
Dest d1 = AutoMapper.Mapper.Map<Source, Dest>(source);
// d1 == null
// I'm looking for a way to configure AutoMapper to
// eliminate this code:
Dest d2 = AutoMapper.Mapper.Map<Source, Dest>(source) ?? new Dest();
推荐答案
(部分地)回答我自己的问题:
Answering my own question (partially):
AutoMapper具有名为AllowNullDestinationValues
的配置属性,默认情况下将其设置为true
.通过将此设置为false
,我可以看到问题中显示的行为,例如:
AutoMapper has a configuration property named AllowNullDestinationValues
which is set to true
by default. By setting this to false
, I get the behavior shown in the question, e.g:
Mapper.Configuration.AllowNullDestinationValues = false;
//...
Source source = null;
Dest d = AutoMapper.Mapper.Map<Source, Dest>(source);
// d is now a new instance of Dest
此解决方案适用于简单类型,其中源类型和目标类型映射良好.对于复杂的映射,我仍然有一些问题(我将更新问题以显示示例).
This solution works OK for simple types, where source and destination types map well. I still have some issues with complex mappings (I will update the question to show an example).
这篇关于AutoMapper:如果source == null,则创建目标类型的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!