使用AutoMapper将字符串映射到枚举

编程入门 行业动态 更新时间:2024-10-28 18:30:05
本文介绍了使用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将字符串映射到枚举

本文发布于:2023-10-23 03:29:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519620.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   AutoMapper

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!