1

Our code currently uses a very old version of Automapper (1.1) to the more recent 3.3. A change in automapper behaviour is causing some problems.

We have fields of type object which may take values that are either reference types or enum values. When the field values are enum values, then Automapper maps the value to the string representation.

See the code example below which illustrates our problem - could someone please tell me how to persuade Automapper to map the enum value to the target enum value.

Thanks in advance - chris

    using AutoMapper;
    using AutoMapper.Mappers;
    using NUnit.Framework;

    namespace AutoMapperTest4
    {
        [TestFixture]
        public class AutomapperTest
        {
            [Test]
            public void TestAutomapperMappingFieldsOfTypeEnumObject()
            {
                // Configure 
                var configuration = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
                var mapper = new MappingEngine(configuration);
                IMappingExpression<Source, Target> parentMapping = configuration.CreateMap<Source, Target>();
                parentMapping.ForMember(dest => dest.Value, opt => opt.MapFrom(s => ConvertValueToTargetEnumValue(s)));

                var source = new Source { Value = SourceEnumValue.Mule };

                var target = mapper.Map<Target>(source);

                Assert.That(target.Value, Is.TypeOf<TargetEnumValue>()); // Fails.  targetParent.Value is a string "Mule".
            }

            private static TargetEnumValue ConvertValueToTargetEnumValue(Source s)
            {
                return (TargetEnumValue)s.Value;
            }
        }

        public enum SourceEnumValue
        {
            Donkey,
            Mule
        }

        public enum TargetEnumValue
        {
            Donkey,
            Mule
        }

        public class Source
        {
            public object Value { get; set; }
        }

        public class Target
        {
            public object Value { get; set; }
        }
    }
Chris Fewtrell
  • 7,555
  • 8
  • 45
  • 63

1 Answers1

1

You can put in an explicit mapping between each enum and object, with a ConvertUsing(e => e) to tell AutoMapper not to mess with the value.

This works, but it's horrid that one has to do it, and in some situations it's difficult to find where to put that code.

I would be very interested to hear from anyone who can suggest a way to get back the "correct" behaviour.

PeteAC
  • 789
  • 8
  • 19