如果我在一个属性中有两个相似的类,那么你能告诉我正确的Mapping方法吗?
// DatabaseCamper.Gender is string that holds either "M" or "F"
// ViewModelCamper.gender is enum of type Gender
我认为它应该是这样的:
Mapper.CreateMap<DatabaseCamper, ViewModelCamper>().ForMember(x => x.Gender, ...
你能完成这个片段吗?
感谢。
UPD。或者让它添加一些盐。如果我在源类中最初没有映射Destination类(本例中为ViewModelCamper)的属性,并且应该计算该值,该怎么办?
答案 0 :(得分:3)
使用IValueResolver(如果要转换为字符串,则使用IValueFormatter)。例如,假设该字段在未指定的情况下可以为空,因为它简化了错误处理...
public class GenderValueResolver : ValueResolver<string, Gender?>
{
protected override Gender? ResolveCore(string source)
{
if (source.StartsWith("M", System.StringComparison.OrdinalIgnoreCase))
{
return Gender.Male;
}
else if (source.StartsWith("F", System.StringComparison.OrdinalIgnoreCase))
{
return Gender.Female;
}
return null;
}
}
public class GenderValueFormatter : ValueFormatter<Gender?>
{
protected override string FormatValueCore(Gender? value)
{
switch (value)
{
case Gender.Male:
return "M";
case Gender.Female:
return "F";
default:
return null;
}
}
}
...使用
.ForMember(dest => dest.Gender, opt => opt.ResolveUsing(typeof(GenderValueResolver)).FromMember(src => src.Gender))
或
.ForMember(dest => dest.Pages, opt => opt.AddFormatter<GenderValueFormatter>())