Automapper 带下划线属性自定义约定的通用自动映射函数

Automapper 带下划线属性自定义约定的通用自动映射函数,automapper,auto-generate,convention,automapper-3,Automapper,Auto Generate,Convention,Automapper 3,我只需要将一些自动生成的类从数据库映射到域/视图模型类。自动生成的类可能有customer\u id之类的名称,我希望将其映射到CustomerId。不知何故,我想用自动映射器注册我自己的约定。我从以下代码开始,但未填充映射对象属性: //应该将源映射到目标的通用方法 公共静态TTarget映射WithUnderlineConvention(TSource源,TTarget目标) { 初始化(cfg=>cfg.AddProfile()); CreateMap(); var-mapped=Mapp

我只需要将一些自动生成的类从数据库映射到域/视图模型类。自动生成的类可能有customer\u id之类的名称,我希望将其映射到CustomerId。不知何故,我想用自动映射器注册我自己的约定。我从以下代码开始,但未填充映射对象属性:

//应该将源映射到目标的通用方法
公共静态TTarget映射WithUnderlineConvention(TSource源,TTarget目标)
{
初始化(cfg=>cfg.AddProfile());
CreateMap();
var-mapped=Mapper.Map(源、目标);
返回映射;
} 
//新下划线配置文件
公共类自动映射配置文件:配置文件
{
公共自动映射配置文件()
{
初始化(配置=>configuration.CreateProfile(“下划线profile”,下划线profile));
assertConfigurationsValid();
}
私有void下划线配置文件(IProfileExpression配置文件)
{
profile.SourceMemberNamingConvention=new PascalCaseNamingConvention();
profile.DestinationMemberNamingConvention=新的SourceUnderlineNameConvention();
}
}
//会议班
公共类SourceUnderlineNameConvention:InAdmingConvention
{
私有只读字符串_separatorCharacter=“_”;
private readonly Regex_splittingExpression=new Regex(@“[\p{Lu}0-9]+(?=?);
公共正则表达式SplittingExpression{get{return}SplittingExpression;}私有集{}
公共字符串分隔符字符{get{return}SeparatorCharacter;}私有集{}
}
//测试用例
[TestMethod()]
公共无效测试\u映射\u数据库\u生成的\u类\u到\u模型()
{
var dbGenerated=新问题类型fromdb()
{
QuestionType_Description=“1”,
问题类型_Id=1,
QuestionType_为_默认值=true,
QuestionType_基于时间=真,
问题类型\序列=1,
问题类型时间单位为秒=1
};
var mappedObject=AutoMapperHelper
.mapWithUndermarkeConvention(dbGenerated,new QuestionType());
mappedObject.QuestionTypeId.Should().Be(dbGenerated.QuestionType\u Id);
mappedObject.QuestionTypeDescription.Should().Be(dbGenerated.QuestionType\u Description);
mappedObject.TimeUnseconds.Should().Be(dbGenerated.QuestionType_Time_In_Seconds);
mappedObject.QuestionTypeSequence.Should().Be(dbGenerated.QuestionType_Sequence);
}
带有AnswerType的公共类测试问题
{
public int QuestionTypeId{get;set;}
公共字符串QuestionTypeDescription{get;set;}
public int QuestionTypeSequence{get;set;}
公共bool questiontypeistimebase{get;set;}
公共int?QuestionTypeTimeInSeconds{get;set;}
公共布尔问题类型默认值{get;set;}
}
如有任何意见,将不胜感激

更新

我发现以下解决方法有效: 我只是用这个->将“下划线”替换为零(Mapper.Initialize(c=>c.ReplaceMemberName(““,”))

publicstaticttargetmapWithUnderlineConvention(TSource-source,ttargettarget)
{
初始化(c=>c.ReplaceMemberName(““,”);
//初始化(cfg=>cfg.AddProfile());
CreateMap();
var-mapped=Mapper.Map(源、目标);
返回映射;
}

您的正则表达式需要更改为:
[\p{L}}0-9]+(?=?)

这将处理客户Id、客户Id、客户Id


{L}unicode类别包括前面提到的Lu、Lt、Ll、Lm和Lo字符。

答案添加在问题的更新部分。基本上,我的解决方案非常简单->映射器。初始化(c=>c.ReplaceMemberName(““,”))

您好,谢谢您的回复。我已将正则表达式更改为您建议的值,但结果仍然相同。我已找到一种可能不是最佳解决方案但对我有效的解决方法。我将更新我的问题解决方案。。。