Using AutoMapper to map a string to an enum

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

    Since you're mapping from the display name and not the enum name you'll need to build a custom mapping function to scan the attributes to find the enum with that display name. You can use ResolveUsing instead of MapFrom to use a custom mapping function:

    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
    }
    

    You could cache the names in a static dictionary so you don't use reflection every time.

    A few methods of doing that can be found here.

提交回复
热议问题