问题是我们有多个thousend数据库表,其属性具有动态后缀(例如:Name_A1234,Name_B4567,Name_H123等属性)。现在我们要使用AutoMapper将此属性映射到具有没有此后缀的属性的DataModel。具有ForMember功能的解决方案是时间膨胀并且还产生太多代码。
我已尝试以下方法解决此问题:
public class A
{
public string Name_XY1234 { get; set; }
}
public class B
{
public string Name_AB1234 { get; set; }
}
public class C
{
public string Name { get; set; }
}
public class MyNamingConvention : INamingConvention
{
private readonly Regex _splittingExpression = new Regex(@"\A[a-zA-Z0-9]+(?=_?.*)");
public string SeparatorCharacter
{
get { return string.Empty; }
}
public System.Text.RegularExpressions.Regex SplittingExpression
{
get { return _splittingExpression; }
}
}
public class Test
{
public Test()
{
try
{
Mapper.Initialize(cfg =>
{
cfg.SourceMemberNamingConvention = new MyNamingConvention();
cfg.DestinationMemberNamingConvention = new MyNamingConvention();
});
AutoMapper.Mapper.CreateMap<A, C>();
var a = new A();
a.Name_XY1234 = "Test";
var c = AutoMapper.Mapper.Map<C>(a);
// should be Test...
System.Diagnostics.Debug.WriteLine(c.Name);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}
不幸的是,这不起作用。
我该如何解决这个问题?
谢谢。