我尝试使用AutoMapper将SourceThing
转换为DestinationThing
public class SourceThing
{
public string Length;
public string Width;
public string Make;
}
public class DestinationThing
{
public int Length;
public int Width;
public string Make;
}
CreateMap<SourceThing, DestinationThing>();
_mapper.Map<DestinationThing>(sourceObj);
我遇到的问题是我的sourceObj
如下:
{
"Length": "",
"Width": "2",
"Make": "3"
}
我收到错误:FormatException: Input string was not in a correct format.
AutoMapperMappingException: Error mapping types.
Property: Length
我是否需要配置一些东西才能让AutoMapper成功映射?
答案 0 :(得分:3)
CreateMap<SourceThing, DestinationThing>()
.ForMember(dest => dest.Length,
opt => opt.MapFrom(src => string.IsNullOrWhiteSpace(src.Length)
? default(int)
: int.Parse(src.Length))