AutoMapper strings to enum descriptions

Posted by 6footunder on Stack Overflow See other posts from Stack Overflow or by 6footunder
Published on 2010-08-11T20:14:30Z Indexed on 2011/01/29 7:26 UTC
Read the original article Hit count: 129

Given the requirement:

Take an object graph, set all enum type properties based on the processed value of a second string property. Convention dictates that the name of the source string property will be that of the enum property with a postfix of "Raw".

By processed we mean we'll need to strip specified characters e.t.c.

I've looked at custom formatters, value resolvers and type converters, none of which seems like a solution for this?

We want to use AutoMapper as opposed to our own reflection routine for two reasons, a) it's used extensively throughout the rest of the project and b) it gives you recursive traversal ootb.

-- Example --

Given the (simple) structure below, and this:

var tmp = new SimpleClass 
  { 
       CountryRaw = "United States",
       Person = new Person { GenderRaw="Male" }
  };

var tmp2 = new SimpleClass();

Mapper.Map(tmp, tmp2);

we'd expect tmp2's MappedCountry enum to be Country.UnitedStates and the Person property to have a gender of Gender.Male.

public class SimpleClass1
{
  public string CountryRaw {get;set;}

  public Country MappedCountry {get;set;}

  public Person Person {get;set;}
}

public class Person
{
  public string GenderRaw {get;set;}

  public Gender Gender {get;set;}

  public string Surname {get;set;}
}

public enum Country
{
  UnitedStates = 1,
  NewZealand = 2
}

public enum Gender
{
  Male,
  Female,
  Unknown
}

Thanks

© Stack Overflow or respective owner

Related posts about conversion

Related posts about enums