Blog

Automapping C# objects from one naming convention to an other

I systematically had a problem for mapping object resulting from a database query following underscore naming convention to objects following C# naming convention.

For instance,

private class DBUser {
  public int user_id { get; set; }
  public string user_name { get; set; }
}
private class User {
  public int UserId { get; set; }
  public string UserName { get; set; }
}

This is obviously not a hard problem. I solved it using Automapper, its profiles and its naming convention. Here is the code:

public class FromDatabase : Profile {
  public override string ProfileName { get { return "FromDatabase"; } }
  protected override void Configure() {
    SourceMemberNamingConvention = new LowerUnderscoreNamingConvention ();
    DestinationMemberNamingConvention = new PascalCaseNamingConvention ();

    CreateMap <DatabaseObject, BusinessObject> ();
  }
}

public class ToDatabase : Profile {
  public override string ProfileName { get { return "ToDatabase"; } }
  protected override void Configure() {
    SourceMemberNamingConvention = new PascalCaseNamingConvention ();
    DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention ();

    CreateMap <BusinessObject, DatabaseObject> ();
  }
}

and

Mapper.Initialize ((obj) => {
    obj.AddProfile (new FromDatabase ());
    obj.AddProfile (new ToDatabase ());
});

Last, I can automagically get my objects with their right convention:

var underscore = new DatabaseObject () { user_name = "ancailliau" };
Console.WriteLine (string.Format ("Hello, I'm {0}!", underscore.user_name));

var pascal = Mapper.Map &lt;DatabaseObject, BusinessObject&gt; (underscore);
Console.WriteLine (string.Format ("Hello, I'm {0}!", pascal.UserName));

pascal = new BusinessObject () { UserName = "pcailliau" };
Console.WriteLine (string.Format ("Hello, I'm {0}!", pascal.UserName));

underscore = Mapper.Map &lt;BusinessObject, DatabaseObject&gt; (pascal);
Console.WriteLine (string.Format ("Hello, I'm {0}!", underscore.user_name));

Nice, no?

Leave a Comment