AutoMapper cannot convert enum to nullable int?

前端 未结 2 692
死守一世寂寞
死守一世寂寞 2021-01-04 22:03

I got AutoMapperMappingException exception

Exception of type \'AutoMapper.AutoMapperMappingException\' was thrown. ---> System.InvalidCastException: I

2条回答
  •  独厮守ぢ
    2021-01-04 22:27

    It looks like no, it won't take care of this automatically for you. Interestingly, it will map an enum to a regular int.

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

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

    Assuming context.SourceValue = DummyTypes.Foo and context.DestinationType is int?, you would end up with:

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

    which throws a similar exception:

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

    So I think really the question is why can't we cast a variable of type enum to int? That question has already been asked here.

    This seems like a bug in AutoMapper. Anyway the workaround is to map the property manually:

    Mapper.CreateMap()
        .ForMember(dest => dest.Dummy, opt => opt.MapFrom(src => (int?)src.Dummy));
    

提交回复
热议问题