Home > other >  How do I map enums in many-to-one relationship
How do I map enums in many-to-one relationship

Time:05-25

I have two enums, the source one is with responses from api and another one is what I want to send to frontend.

public enum ApiResponse
{
    A=1,
    B=2,
    C=3,
    D=4
}


public enum DestEnum
{
    A=1,
    BCD=2
}

What I am trying to do is:

public class ExampleViewModel
{
    public DestEnum foo { get; set; }
}

var response = ApiResponse.C;

result = new ExampleViewModel()
{
    foo = response
};

And I want foo value to be DestEnum.BCD Is it possible to do with automapper or some custom attributes?

CodePudding user response:

Assuming you've set your serializer up to send strings already you seem to be just looking for a way to map an X to a Y

How about:

public static class EnumExtensions{
  static Dictionary<ApiResponse,DestEnum> _mapDest = 
  new() {
      [ApiResponse.A] = DestEnum.A,
      [ApiResponse.B] = DestEnum.BCD,
      [ApiResponse.C] = DestEnum.BCD,
      [ApiResponse.D] = DestEnum.BCD,
      
  };
    
  public static DestEnum AsDest(this ApiResponse x) => _mapDest[x];
}

And then you can convert the ApiRespnse you got to a Dest like:

return new BlahViewModel{

  DestEnumProperty = apiResponseEnumValueIGot.AsDest(),
  OtherProp = ...
}

Warning, the lookup will blow up if you get any values that aren't mapped; if you think this will ever be possible, consider having an Unknown value in your DestEnum and doing something like:

=> _mapDest.TryGetValue(x, out var r) ? r : DestEnum.Unknown
  • Related