简体   繁体   中英

Map long to enum using automapper

I have a problem converting long value to enum using automapper. If I do nothing I get exception

Missing type map configuration or unsupported mapping.

Mapping types: Int64 -> SomeEnum

So if I add mapping configuration it works

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

However I have to define it for every enum in solution, is there a way to define a general rule for converting long to enums in automapper?

It seems that this is impossible. But you can simplify the addition of conversion for enums using the factory:

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

Then your code:

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

PS: In the example you have int size enum, use the long type ( doc ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM