Reputation: 19903
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>();
}
}
Upvotes: 5
Views: 4476
Reputation: 11
Note for name conversion Target.AB -> Source.AB but not Source.A_B To fix this implement your PascalCaseNamingConvention with modifed RegExpression (\p{Lu}(?=$|\p{Lu})|\p{Lu}?[\p{Ll}0-9]+)
public class MyPascalCaseNamingConvention : INamingConvention
{
private static readonly Regex PascalCase = new Regex(@"(\p{Lu}(?=$|\p{Lu})|\p{Lu}?[\p{Ll}0-9]+)");
public static readonly MyPascalCaseNamingConvention Instance = new MyPascalCaseNamingConvention();
public Regex SplittingExpression { get; } = PascalCase;
public string SeparatorCharacter => string.Empty;
public string ReplaceValue(Match match) => match.Value[0].ToString().ToUpper() + match.Value.Substring(1);
}
Upvotes: 0
Reputation: 887
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();
}
}
Upvotes: 1