Turning around to D Stanley , answer a little higher and change the EnumHelper class from this other discussion to focus on yours since this question really covers two areas, AutoMapper and getting the Enum value from the string correctly.
Gain D Stanley's original answer:
public static class QuestionAutoMapperConfig { public static void ConfigureAutoMapper() { Mapper.CreateMap<Profile, ProfileDTO>() .ForMember(d => d.SchoolGrade, op => op.ResolveUsing(o => MapGrade(o.SchoolGrade))); } public static SchoolGradeDTO MapGrade(string grade) {
I adjusted EnumHelper from the above example to quickly show a parameter in which you can modify the Parse method to try the standard Enum.Parse () first, and not get an attempt to make a more detailed comparison of Enum, creating a dictionary of values based either on the name of the enumeration name , or the attribute text is displayed on it (if used).
public static class EnumHelper<T> { public static IDictionary<string, T> GetValues(bool ignoreCase) { var enumValues = new Dictionary<string, T>(); 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<string, T> 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); } }
Scott source share