Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper - mapping 2 enum values to 1 value

Tags:

c#

automapper

I'm a complete noob to Automapper and I'm wondering if its possible to map 2 enum values in the source to 1 in the destination.

In the example below I want to map both VisaCredit and VisaDebit to Visa.

Source:

public enum CardType { VisaCredit, VisaDebit, MasterCard, AmericanExpress, SwitchMaestro }

Destination:

public enum CardType { Visa, MasterCard, AmericanExpress, SwitchMaestro }
like image 938
BrightonDev Avatar asked Jul 29 '26 05:07

BrightonDev


1 Answers

You could create a mapping for those types, then define a custom converter:

Mapper.CreateMap<X.CardType, Y.CardType>().ConvertUsing(CardTypeConverter.Convert);

Your card type mapping function would look something similar to this (other mappings omitted for brevity):

public class CardTypeConverter
{
    public static Y.CardType Convert(X.CardType cardType)
    {
        switch(cardType)
        {
            ...

            case X.CardType.VisaCredit:
            case X.CardType.VisaDebit:
                return Y.CardType.Visa;

            ...
        }
    }
}

This might not be the most succinct method available for mapping two enum values to one, but it should work.

like image 155
Chris Mantle Avatar answered Jul 31 '26 19:07

Chris Mantle