简体   繁体   中英

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM