AutoMapper无法将枚举转换为可空的int?

Pet*_*ann 9 automapper

我得到了AutoMapperMappingException异常

抛出了"AutoMapper.AutoMapperMappingException"类型的异常.---> System.InvalidCastException:从'DummyTypes'到'System.Nullable`1 [[System.Int32,...]的无效转换

什么时候

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);
}
Run Code Online (Sandbox Code Playgroud)

AutoMapper不应该隐式地映射这个没有任何额外的显式规则吗?

PS我无法将DummyDestination.Dummy的定义更改为枚举.我必须处理这样的接口.

And*_*ker 17

看起来不行,它不会自动为您解决这个问题.有趣的是,它映射enum到常规int.

看看AutoMapper的来源,我认为有问题的一行是:

Convert.ChangeType(context.SourceValue, context.DestinationType, null);
Run Code Online (Sandbox Code Playgroud)

假设context.SourceValue = DummyTypes.Foocontext.DestinationTypeint?,你最终会得到:

Convert.ChangeType(DummyTypes.Foo, typeof(int?), null)
Run Code Online (Sandbox Code Playgroud)

这引发了类似的异常:

从'UserQuery + DummyTypes'到'System.Nullable`1 [[System.Int32,mscorlib,Version = 4.0.0.0]的无效演员表

所以我认为真正的问题是为什么我们不能将变量类型转换enumint? 这个问题已经在这里提出过了.

这似乎是AutoMapper中的一个错误.无论如何,解决方法是手动映射属性:

Mapper.CreateMap<DummySource, DummyDestination>()
    .ForMember(dest => dest.Dummy, opt => opt.MapFrom(src => (int?)src.Dummy));
Run Code Online (Sandbox Code Playgroud)