【问题标题】:Automapper ignore null values but do map empty string to nullAutomapper 忽略 null 值,但将空字符串映射到 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?

【问题讨论】:

    标签: c# .net string null automapper


    【解决方案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);
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 2014-10-15
      相关资源
      最近更新 更多