Automapper, INamingConvention Camelcase properties to uppercase with underscore

不问归期 提交于 2019-12-10 15:26:25

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/12000466/automapper-inamingconvention-camelcase-properties-to-uppercase-with-underscore

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!