本文介绍了使用AutoMapper将字符串映射到枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下类domain和Dto类:
I have the following classes domain and Dto classes:
public class Profile { public string Name { get; set; } public string SchoolGrade { get; set; } } public class ProfileDTO { public string Name { get; set; } public SchoolGradeDTO SchoolGrade { get; set; } } public enum SchoolGradeDTO { [Display(Name = "Level One"] LevelOne, [Display(Name = "Level Two"] LevelTwo, }我使用以下方法:
Mapper.CreateMap<Profile, ProfileDTO>() .ForMember(d => d.SchoolGrade , op => op.MapFrom(o => o.SchoolGrade))然后,出现以下错误:
未找到请求的值二级".
Requested value 'Level Two' was not found.
如何正确映射?
推荐答案由于您是根据显示名称而不是 enum 名称进行映射提供了一个自定义映射函数来扫描属性以查找具有该显示名称的枚举.您可以使用ResolveUsing代替MapFrom来使用自定义映射功能:
Since you're mapping from the display name and not the enum name you'll need to buid 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<Profile, ProfileDTO>() .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.
更多推荐
使用AutoMapper将字符串映射到枚举
发布评论