简体   繁体   中英

Multiple Automapper Naming Conventions

I have a situation where I want to map using lower underscore to pascal going one way, but pascal to lower underscore the other way. My understanding is that profiles can do this, but I'm struggling with getting it to work. Here's what I have:

   Mapper.Initialize(cfg =>
            {
                cfg.AddProfile<FromUnderscoreMapping>();
                cfg.AddProfile<ToUnderscoreMapping>();
            });

   Mapper.CreateMap<ArticleEntity, Article>().WithProfile("FromUnderscoreMapping");

...

        public class FromUnderscoreMapping : Profile
        {
            protected override void Configure()
            {
                SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
                DestinationMemberNamingConvention = new PascalCaseNamingConvention();
            }

            public override string ProfileName
            {
                get { return "FromUnderscoreMapping"; }
            }
        }

        public class ToUnderscoreMapping : Profile
        {
            protected override void Configure()
            {
                SourceMemberNamingConvention = new PascalCaseNamingConvention();
                DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention();
            }

            public override string ProfileName
            {
                get { return "ToUnderscoreMapping"; }
            }
        }

The mapping needs to be moved to the config:

public class FromUnderscoreMapping : Profile
{
    protected override void Configure()
    {
        SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
        DestinationMemberNamingConvention = new PascalCaseNamingConvention();
        CreateMap<ArticleEntity, Article>();
    }

    public override string ProfileName
    {
        get { return "FromUnderscoreMapping"; }
    }
}

public class ToUnderscoreMapping : Profile
{
    protected override void Configure()
    {
        SourceMemberNamingConvention = new PascalCaseNamingConvention();
        DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention();
        CreateMap<Article, ArticleEntity>();
    }

    public override string ProfileName
    {
        get { return "ToUnderscoreMapping"; }
    }
}

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