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);
        }
    }
}
Eli Pulsifer
  • 713
  • 9
  • 25
  • 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. – Eli Pulsifer Feb 28 '19 at 02: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](https://github.com/AutoMapper/AutoMapper.Collection). – Lucian Bargaoanu Feb 28 '19 at 05: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. – Eli Pulsifer Mar 01 '19 at 03:00
  • [Yes](http://docs.automapper.org/en/latest/Conditional-mapping.html#preconditions). AutoMapper.Collection. – Lucian Bargaoanu Mar 01 '19 at 05:44

0 Answers0