使用自动映射器将 long 映射到枚举

Map long to enum using automapper

我在使用自动映射器将长值转换为枚举时遇到问题。如果我什么都不做,我会得到异常

Missing type map configuration or unsupported mapping.

Mapping types: Int64 -> SomeEnum

所以如果我添加映射配置它就可以工作

public enum B
{
    F1,
    F2
}

public class A
{
    public B FieldB { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var autoMapper = new Mapper(new MapperConfiguration(expression =>
            {
                expression.CreateMap<long, B>()
                    .ConvertUsing(l => (B)l);
            }));
        var dictionary = new Dictionary<string, object>()
        {
            {"FieldB", 1L}
        };
        var result = autoMapper.Map<A>(dictionary);
    }
}

但是我必须为解决方案中的每个枚举定义它,有没有办法定义在自动映射器中将 long 转换为枚举的一般规则?

看来这不可能。但是您可以使用工厂简化枚举的转换添加:

public class CommonMappingProfile : Profile
{
    public CommonMappingProfile()
    {
        CreateMapLongToEnum<B>();
    }

    private void CreateMapLongToEnum<T>() where T : Enum
    {
        CreateMap<long, T>().ConvertUsing(l => (T)Enum.ToObject(typeof(T) , l));
    }
}

public class MapperConfigFactory
{
    public MapperConfiguration Create(Action<IMapperConfigurationExpression> configExpression = null)
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<CommonMappingProfile>();
            configExpression?.Invoke(cfg);
        });
        return config;
    }
}

然后你的代码:

var autoMapperConfigFactory = new MapperConfigFactory();
var autoMapper = new Mapper(autoMapperConfigFactory.Create(cfg =>
{
    /* Custom settings if required */               
}));
var result = autoMapper.Map<A>(dictionary);

PS:在您有 int 大小枚举的示例中,使用 long 类型 (doc)。