Using AutoMapper to map a string to an enum

前端 未结 3 2233
一整个雨季
一整个雨季 2021-02-12 13:14

I have the following classes domain and Dto classes:

public class Profile
{
   public string Name { get; set; }
   public string SchoolGrade { get; set; } 
}

pu         


        
3条回答
  •  天命终不由人
    2021-02-12 13:34

    in mapping configuration

    {
    CreateMap().ConvertUsing>();
    }
    

    converters

    public class StringToEnumConverter : ITypeConverter, ITypeConverter where T : struct
        {
            public T Convert(ResolutionContext context)
            {
                T t;
                if (Enum.TryParse(source, out t))
                {
                    return t;
                }
    
                var source = (string)context.SourceValue;
                if (StringToEnumBase.HasDisplayAttribute())
                {
                    var result = StringToEnumBase.Parse(source);
                    return result;
                }
    
                throw new ConverterException();
            }
    
            T? ITypeConverter.Convert(ResolutionContext context)
            {
                var source = (string)context.SourceValue;
                if (source == null) return null;
    
                return Convert(context);
            }
        }
    
        public static class StringToEnumBase where T:struct
            {
                public static T Parse(string str)
                {
                    var type = typeof (T);
    
                    var enumMembers = type.GetMembers(BindingFlags.Public | BindingFlags.Static);
    
                    var enumMembersCollection = enumMembers
                        .Select(enumMember => new
                        {
                            enumMember,
                            attributes = enumMember.GetCustomAttributes(typeof(DisplayAttribute), false)
                        })
                        .Select(t1 => new
                        {
                            t1, value = ((DisplayAttribute) t1.attributes[0]).Name
                        })
                        .Select(t1 => new Tuple(t1.value, t1.t1.enumMember.Name))
                        .ToList();
                    var currentMember = enumMembersCollection.FirstOrDefault(item => item.Item1 == str);
                    if (currentMember == null) throw new ConverterException();
    
                    T t;
                    if (Enum.TryParse(currentMember.Item2, out t))
                    {
                        return t;
                    }
    
                    throw new ConverterException();
                }
    
                public static bool HasDisplayAttribute()
                {
                    var type = typeof (T);
                    var attributes = type.GetCustomAttributes(typeof(DisplayAttribute), false);
                    return attributes.Length > 0;
                }
            }
    

提交回复
热议问题