0

I found this post describing how to conditionally copy values over a destination object if they are not null.

Works great except for list members, it always overwrites them with an empty list. I'm not sure if I've just not configured the mapper correctly or if this is a bug. The following program demonstrates the issue.

namespace automapper_test
{
    using AutoMapper;
    using System;
    using System.Collections.Generic;

    class Program
    {
        class Test
        {
            public int? A { get; set; }
            public string B { get; set; }
            public Guid? C { get; set; }
            public List<Guid> D { get; set; }
        }

        static void Main(string[] args)
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AllowNullCollections = true;
                cfg.CreateMap<Test, Test>().ForAllMembers(opt => opt.Condition((src, dest, member) => member != null));
            });

            var mapper = config.CreateMapper();

            var source = new Test { A = 2, C = Guid.Empty };
            var target = new Test { A = 1, B = "hello", C = Guid.NewGuid(), D = new List<Guid> { Guid.NewGuid() } };

            mapper.Map(source, target);

            System.Diagnostics.Debug.Assert(target.D.Count == 1);
        }
    }
}
4
  • So, interestingly its not actually overwriting the list its just removing all the elements. I put an object id on the list and its the same before and after mapping. Commented Feb 28, 2019 at 2:36
  • When mapping to an existing collection, the destination collection is cleared first. If this is not what you want, take a look at AutoMapper.Collection. Commented Feb 28, 2019 at 5:00
  • I'm fine with that behavior if the condition is met but in this case the condition is not met and the destination should not be modified. From this behavior it appears the condition is evaluated after the destination is initialized. Commented Mar 1, 2019 at 3:00
  • Yes. AutoMapper.Collection. Commented Mar 1, 2019 at 5:44

0

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.