0

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?

1 Answer 1

2

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

        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.