简体   繁体   中英

Automapper ignore null values but do map empty string to null

We are using automapper. I want to map two objects of the same type. When the source member value = null, then the destination member should be used. However when the source member value is an empty string (""), I want the destination member to become null. Here is an example code:

        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);

        }

This however will fail. mappedo.text will be "not empty". Do you have a suggestion how to achieve all members of type string to become null when the source member is an empty string?

Changing the conditions will do the trick:

        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);

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM