c# - Automapper Map All Members of Certain Destination Type
问题描述
I'm loading data from a third-party API where one of the objects contain a list of attributes that can be one of several values. For example:
{
"name": "blah",
"permissions": {
"action_1": "allowed",
"action_2": "not_allowed",
"action_3": "allowed",
"action_4": "not_allowed",
"action_5": "limited",
"action_6": "limited"
}
}
The value for each permission can be allowed
, not_allowed
, or limited
. My API response permissions model has these mapped to strings for simplicity, but I need to map these to an Enum when converting to my data model. I know I can map each property individually like so:
public class MyProfile : Profile {
public MyProfile()
{
CreateMap<ApiResponsePermissions, Permissions>()
.ForMember(dest => dest.Action1, o => o.MapFrom(s => MapPermission(s.Action1)))
.ForMember(dest => dest.Action2, o => o.MapFrom(s => MapPermission(s.Action2)))
.ForMember(dest => dest.Action3, o => o.MapFrom(s => MapPermission(s.Action3)))
.ForMember(dest => dest.Action4, o => o.MapFrom(s => MapPermission(s.Action4)))
.ForMember(dest => dest.Action5, o => o.MapFrom(s => MapPermission(s.Action5)))
.ForMember(dest => dest.Action6, o => o.MapFrom(s => MapPermission(s.Action6)));
}
static PermissionEnum MapPermission(string permission)
{
// ...
}
}
I also know I can use ForAllMembers
to map every property, but can that be used to map specific properties based on the destination type? The actual destination class has other properties besides the permissions.
Relevant Classes:
public class Permissions {
public int Id { get; set; }
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
public PermissionEnum Action1 { get; set; }
public PermissionEnum Action2 { get; set; }
public PermissionEnum Action3 { get; set; }
public PermissionEnum Action4 { get; set; }
public PermissionEnum Action5 { get; set; }
public PermissionEnum Action6 { get; set; }
}
public class ApiResponsePermissions {
public string Action1 { get; set; }
public string Action2 { get; set; }
public string Action3 { get; set; }
public string Action4 { get; set; }
public string Action5 { get; set; }
public string Action6 { get; set; }
}
public enum PermissionEnum {
NotAllowed,
Allowed,
Limited
}
解决方案
推荐阅读
- c++11 - 在另一个 `std::array` 中使用 `std::array` 大小
- javascript - Chrome中JS多个PDF下载限制为10个
- xcode - 安装命令行开发人员工具:无法安装该软件,因为它当前无法从软件更新服务器获得
- sql - 如何在加入 2 个表时在 sql 中的键上添加不同的关键字
- ios - 是否可以从 TestFlight 用户那里检索错误日志消息?
- jquery - 网站未正确调整到移动设备的大小(元值到位)
- python - 包含 if 语句的 while 循环的问题
- javascript - 如何让 webview findInPage() 在 Electron 中工作
- javascript - 如何 console.log 列表的一部分?
- swift - 颜色 rgb 初始化程序在 SwiftUI 中不能作为背景工作