Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper, INamingConvention Camelcase properties to uppercase with underscore

I have two classes one generetad by Entity Framework, the other is the class I use everywhere.

My Class :

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

EF class :

public class PERSON
{
    public string FIRST_NAME { get; set; }
    public string LAST_NAME { get; set; }
}

I found the solution when the source is PERSON to Person, but I don't find the solution for Person to PERSON (the properties are in uppercase and underscore separator).

The solution for PERSON to Person :

Mapper.Initialize(x => x.AddProfile<Profile1>());
var res = Mapper.Map<PERSON, Person>(person);

public class UpperUnderscoreNamingConvention : INamingConvention
{
    private readonly Regex _splittingExpression = new Regex(@"[p{Lu}0-9]+(?=_?)");
    public Regex SplittingExpression
    {
        get { return _splittingExpression; }
    }

    public string SeparatorCharacter
    {
        get { return "_"; }
    }
}

public class Profile1 : Profile
{
    protected override void Configure()
    {
        SourceMemberNamingConvention = new UpperUnderscoreNamingConvention();
        DestinationMemberNamingConvention = new PascalCaseNamingConvention();
        CreateMap<PERSON, Person>();
    }
}
like image 795
Kris-I Avatar asked Nov 14 '22 00:11

Kris-I


1 Answers

This is working for version 7.0.1 of AutoMapper:

using AutoMapper;
using System.Text.RegularExpressions;


namespace Data.Service.Mapping
{
    public class UpperUnderscoreNamingConvention: INamingConvention
    {
        public Regex SplittingExpression { get; } = new Regex(@"[\p{Ll}\p{Lu}0-9]+(?=_?)");

        public string SeparatorCharacter => "_";

        public string ReplaceValue(Match match) => match.Value.ToUpper();
    }
}
like image 114
Papa Stahl Avatar answered Dec 22 '22 08:12

Papa Stahl