05 September 2010

Mapping enums with Automapper

If no map is created then first name-based then value-based mapping is applied.

If map is created value-based mapping is used.

Results only differ for values with same names but different values.

enum One { Value = 3, Name1 = 7, Unique1 = 8 }
enum Two { Value = 5, Name2 = 7, Unique2 = 9 }

static void PrintMapped(One one)
{
    Console.WriteLine("{0,7} --> {1}", one, Mapper.Map<One, Two>(one));
}

static void PrintAllMappings()
{
    Console.ForegroundColor = ConsoleColor.Cyan;
    Console.WriteLine("{0,7} --> {1}", "One", "Two");

    Console.ForegroundColor = ConsoleColor.Gray;
    PrintMapped((One)1);
    PrintMapped(One.Value);
    PrintMapped(One.Name1);
    PrintMapped(One.Unique1);

    Console.WriteLine();
}

static void Main(string[] args)
{
    PrintAllMappings();

    Mapper.CreateMap<One, Two>();
    PrintAllMappings();

    Console.WriteLine("Press ENTER to finish");
    Console.ReadLine();
}

Output:
    One --> Two
      1 --> 1
  Value --> Value
  Name1 --> Name2
Unique1 --> 8

    One --> Two
      1 --> 1
  Value --> 3
  Name1 --> Name2
Unique1 --> 8

No comments: