当前位置: 动力学知识库 > 问答 > 编程问答 >

automapper - Type Mapper between INT32[] and IList<SomeENUM>

问题描述:

I need to convert Int32[] to IList, where RoleModel is an enum, and I have:

CreateMap<Int32, RoleModel>()

This is not applied when I convert Int32[] to List. So I tried:

CreateMap<Int32[], IList<RoleModel>>().ConvertUsing(x => x.Select(y => (RoleModel)y).ToList());

And this works ... Isn't this strange? Shouldn't the first option work?

Thank You,

Miguel

网友答案:

Try this it works.

public enum RoleModel
{
    None = 0,
    RoleModel1 = 1,
    RoleModel2 = 2,
    RoleModel3 = 3
}

class Program
{
    static void Main(string[] args)
    {
        Mapper.CreateMap<int, RoleModel>().ConvertUsing<IntToEnumConver>();
        var roleModel = Mapper.Map<int, RoleModel>(2);
        var lstInt = new List<int> { 3, 2, 1 };
        var roleModels = Mapper.Map<IList<int>, IList<RoleModel>>(lstInt);
    }
}

public class IntToEnumConver : ITypeConverter<int, RoleModel>
{
    public RoleModel Convert(ResolutionContext context)
    {
        var source = context.SourceValue as int?;
        if (Enum.IsDefined(typeof(RoleModel), source))
        {
            return (RoleModel)source;
        }
        else
        {
            // Throw exception or Retrun None, etc.
            return RoleModel.None;
        }
    }
}

Also, If you want use array instead of List<T> use below.

var lstInt = new[] { 3, 2, 1 };
var roleModels = Mapper.Map<int[], IList<RoleModel>>(lstInt);
分享给朋友:
您可能感兴趣的文章:
随机阅读: