本文介绍了AutoMapper无法将枚举转换为可为null的int吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了AutoMapperMappingException异常

I got AutoMapperMappingException exception

何时

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

如果没有任何额外的显式规则,AutoMapper是否应该隐式映射此映射?

Should not AutoMapper map this implicitly without any extra explicit rule?

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

P.S. I cannot change the definition of DummyDestination.Dummy to enum. I have to deal with such interfaces.

推荐答案

似乎不,它不会自动为您处理.有趣的是,它映射enum到常规int.

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

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

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

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

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

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

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

会引发类似的异常:

所以我认为真正的问题是为什么我们不能将类型为enum的变量强制转换为int? 已经在这里被问到了.

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.

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

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

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

这篇关于AutoMapper无法将枚举转换为可为null的int吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 16:25