Using AutoMapper to map a string to an enum

前端 未结 3 2196
一整个雨季
一整个雨季 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:55

    Expanding on D Stanley's answer from above in a little more detail, and modified the EnumHelper class from this other discussion to focus on your specific situation as this question really spans two areas, AutoMapper and correctly obtaining an Enum's value from a string.

    Enhancing D Stanley's original answer:

    public static class QuestionAutoMapperConfig
    {
        public static void ConfigureAutoMapper()
        {
            Mapper.CreateMap()
                .ForMember(d => d.SchoolGrade,
                    op => op.ResolveUsing(o => MapGrade(o.SchoolGrade)));
        }
    
        public static SchoolGradeDTO MapGrade(string grade)
        {
            //TODO: function to map a string to a SchoolGradeDTO
            return EnumHelper.Parse(grade);
        }
    }
    

    I have adjusted the EnumHelper from the mentioned example to quickly show an option where by you could modify the Parse method to first try the standard Enum.Parse(), and failing that to try to do a more detailed comparison of the Enum type by creating a dictionary of the values based either on the enum value name, or it's Display attribute text (if used).

    public static class EnumHelper
    {
        public static IDictionary GetValues(bool ignoreCase)
        {
            var enumValues = new Dictionary();
    
            foreach (FieldInfo fi in typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public))
            {
                string key = fi.Name;
    
                var display = fi.GetCustomAttributes(typeof(DisplayAttribute), false) as DisplayAttribute[];
                if (display != null)
                    key = (display.Length > 0) ? display[0].Name : fi.Name;
    
                if (ignoreCase)
                    key = key.ToLower();
    
                if (!enumValues.ContainsKey(key))
                    enumValues[key] = (T)fi.GetRawConstantValue();
            }
    
            return enumValues;
        }
    
        public static T Parse(string value)
        {
            T result;
    
            try
            {
                result = (T)Enum.Parse(typeof(T), value, true);
            }
            catch (Exception)
            {
                result = ParseDisplayValues(value, true);
            }
    
    
            return result;
        }
    
        private static T ParseDisplayValues(string value, bool ignoreCase)
        {
            IDictionary values = GetValues(ignoreCase);
    
            string key = null;
            if (ignoreCase)
                key = value.ToLower();
            else
                key = value;
    
            if (values.ContainsKey(key))
                return values[key];
    
            throw new ArgumentException(value);
        }
    }
    

提交回复
热议问题