本文介绍了使用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))
然后,出现以下错误:
如何正确映射?
推荐答案
由于您是根据显示名称而不是 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将字符串映射到枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!