Dsbdev
Dsbdev

Reputation: 21

Mapping null source values into destination

When mapping a source instance to a destination instance, how are null source values handled? It appears that with built in types, a null source value will overwrite a destination value (set it to null). However with a navigation property, a destination value will not be set to null by a null source value, e.g. OuterDest.Innter:

`

        public class OuterSource
        {
            public int Value { get; set; }
            public InnerSource? Inner { get; set; }
        }

        public class InnerSource
        {
            public int OtherValue { get; set; }
        }

        public class OuterDest
        {
            public int Value { get; set; }
            public InnerDest? Inner { get; set; }
        }

        public class InnerDest
        {
            public int OtherValue { get; set; }
        }

`

This test will fail

       [TestMethod]
        public void NestedTestNullSourceValue()
        {
            var mappingConfig = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<OuterSource, OuterDest>();
                cfg.CreateMap<InnerSource, InnerDest>();
            });

            var mapper = mappingConfig.CreateMapper();

            OuterSource source = new()
            {
                Value = 123
            };

            OuterDest dest = new()
            {
                Value = 888,
                Inner = new()
                {
                    OtherValue = 999
                }
            };

            mapper.Map(source, dest);
            Assert.AreEqual(123, dest.Value);
            Assert.IsNull(dest.Inner);
        }

Upvotes: 0

Views: 281

Answers (1)

DavisZ
DavisZ

Reputation: 149

Had the same issue (AutoMapper - Map(source, destination) overwrite destination child object with null value from source via configuration), updating to AutoMapper 12.0.1 pre-release solved my issue

Upvotes: 1

Related Questions