AutoMapper - 将空字符串映射到int

时间:2018-03-30 15:49:30

标签: c# automapper

我尝试使用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成功映射?

1 个答案:

答案 0 :(得分:3)

您需要Custom Value Resolvers

CreateMap<SourceThing, DestinationThing>()
    .ForMember(dest => dest.Length, 
        opt => opt.MapFrom(src => string.IsNullOrWhiteSpace(src.Length)
            ? default(int)
            : int.Parse(src.Length))