Automapper 忽略 null 值,但将空字符串映射到 null

Posted

技术标签:

【中文标题】Automapper 忽略 null 值,但将空字符串映射到 null【英文标题】:Automapper ignore null values but do map empty string to null 【发布时间】:2021-05-16 09:07:36 【问题描述】:

我们正在使用自动映射器。我想映射两个相同类型的对象。当源成员值 = null 时,应使用目标成员。但是,当源成员值为空字符串 ("") 时,我希望目标成员变为空。这是一个示例代码:

        public class someobject
        
            public string text  get; set; 
        

        [TestMethod]
        public void EmptyStringMap()
        
            var cfg = new MapperConfiguration(c => c.CreateMap<someobject, someobject>()
                .AddTransform<string>(s => string.IsNullOrEmpty(s) ? null : s)
                .ForAllOtherMembers(o =>
                    o.Condition((src, dest, srcmember) => srcmember != null)));

            var map = cfg.CreateMapper();

            var desto = new someobject()  text = "not empty" ;
            var srco = new someobject()  text = "" ;

            var mappedo = map.Map(srco, desto);
            Assert.IsNull(mappedo.text);

        

然而这会失败。 mappedo.text 将“不为空”。你有什么建议,当源成员为空字符串时,如何实现string类型的所有成员都为null?

【问题讨论】:

【参考方案1】:

改变条件就行了:

        public class someobject
        
            public string text  get; set; 
        

        [TestMethod]
        public void EmptyStringMap()
        
            var cfg = new MapperConfiguration(c => 
                c.CreateMap<someobject, someobject>()
                .AddTransform<string>(s => string.IsNullOrEmpty(s) ? null : s)
                .ForAllOtherMembers(o =>
                    o.Condition((src, dest, srcmember, destmember) => srcmember != null || destmember.GetType() == typeof(string)));
                );

            var map = cfg.CreateMapper();

            var desto = new someobject()  text = "not empty" ;
            var srco = new someobject()  text = "" ;
            //var srco = new someobject()  text = null ;

            var mappedo = map.Map(srco, desto);
            Assert.IsNull(mappedo.text);

        

【讨论】:

以上是关于Automapper 忽略 null 值,但将空字符串映射到 null的主要内容,如果未能解决你的问题,请参考以下文章