epitka
epitka

Reputation: 17657

AutoMapper: setup member name matching convention

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);
                                      };

Upvotes: 1

Views: 1654

Answers (3)

Fitzchak Yitzchaki
Fitzchak Yitzchaki

Reputation: 9163

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.

Upvotes: 0

epitka
epitka

Reputation: 17657

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

Upvotes: 0

Jimmy Bogard
Jimmy Bogard

Reputation: 26785

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");

Upvotes: 1

Related Questions