首页 > 解决方案 > 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#.netautomapper

解决方案


推荐阅读