tags:

views:

249

answers:

3

I tried setting up a member name mapping convention so that the source members ending with a "Id" are mapped to destination members without Id. For example

UserId -> User

How does one do this? I tried using SourceMemberNameTransformer without success. Also tried using RecognizePostfixes().

    this.SourceMemberNameTransformer = s =>
                                      {     
                                          return s.Replace("Id", string.Empty);
                                      };
A: 

This should to work:

this.SourceMemberNameTransformer = s =>
          {
              if (s.EndsWith("Id"))
                  return s.Substring(0, s.Length - 2);               
              return s;
          };

You also can try achieve that with DestinationMemberNamingConvention and regex.

Mendy
This is same as what I have ?
epitka
Yes. but yours risking any string that contain 'id', like Bid. ans EndsWith by default is case secretive so it is more safe.
Mendy
String.Replace is case sensitive as well - *This method performs an ordinal (case-sensitive and culture-insensitive) search to find oldValue*. http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
statenjason
+1  A: 

You can also use the "RecognizePostfixes" method:

this.RecognizePostfixes("Id");

The built-in transformer is this, just for future reference:

s => Regex.Replace(s, "(?:^Get)?(.*)", "$1");
Jimmy Bogard
A: 

As of now this does not seem to work when setting it in the Profile. Neither SourceMemberNameTransofmer or RecognizePostfix work in Profile. However is specified in Automapper global configuration it works fine.

epitka