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