AutoMapper can't convert enum to nullable int?

I got an AutoMapperMappingException

An exception of type "AutoMapper.AutoMapperMappingException" was thrown. ---> System.InvalidCastException: Invalid listing from 'DummyTypes' to' System.Nullable`1 [[System.Int32, ...

when

public enum DummyTypes : int { Foo = 1, Bar = 2 } public class DummySource { public DummyTypes Dummy { get; set; } } public class DummyDestination { public int? Dummy { get; set; } } [TestMethod] public void MapDummy() { Mapper.CreateMap<DummySource, DummyDestination>(); Mapper.AssertConfigurationIsValid(); DummySource src = new DummySource() { Dummy = DummyTypes.Bar }; Mapper.Map<DummySource, DummyDestination>(src); } 

Should AutoMapper not display this implicitly without any additional explicit rule?

PS I can’t change the definition of DummyDestination.Dummy for listing. I have to deal with such interfaces.

+7
source share
2 answers

It seems no, he will not take care of this automatically for you. Interestingly, it will map enum to a regular int .

Looking at the source of AutoMapper, I think the problematic line is :

 Convert.ChangeType(context.SourceValue, context.DestinationType, null); 

Assuming context.SourceValue = DummyTypes.Foo and context.DestinationType is int? , You'll get:

 Convert.ChangeType(DummyTypes.Foo, typeof(int?), null) 

which raises a similar exception:

Invalid listing from 'UserQuery + DummyTypes' for' System.Nullable`1 [[System.Int32, mscorlib, Version = 4.0.0.0

So, I think, really the question is, why can't we use a variable like enum to int? This question has already been asked here .

This seems like a bug in AutoMapper. In either case, the workaround is to manually display the property:

 Mapper.CreateMap<DummySource, DummyDestination>() .ForMember(dest => dest.Dummy, opt => opt.MapFrom(src => (int?)src.Dummy)); 
+15
source

Just in case, if someone wants to try using a type converter

 Mapper.CreateMap<int?, DummyTypes.Foo?>().ConvertUsing(new FooTypeConverter()); public class FooTypeConverter: TypeConverter<int?, DummyTypes.Foo?> { protected override DummyTypes.Foo? ConvertCore(int? source) { return source.HasValue ? (DummyTypes.Foo?)source.Value : null; } } 

Greetings

-one
source

All Articles