AutoMapper映射异常:空字符串转int类型时抛出FormatException
解决AutoMapper空字符串转int抛出FormatException的问题
这问题太常见了!你碰到的情况是:当SourceThing里的Length是空字符串时,AutoMapper默认会直接调用int.Parse()来转换类型,可空字符串根本没法转成int,自然就炸FormatException了。下面给你几个实用的解决方案:
方案1:针对单个字段设置映射逻辑
最直接的方式就是在创建映射规则时,给Length和Width字段加个空值判断,转不成int就用默认值(比如0):
CreateMap<SourceThing, DestinationThing>() .ForMember(dest => dest.Length, opt => opt.MapFrom(src => string.IsNullOrEmpty(src.Length) ? 0 : int.Parse(src.Length))) .ForMember(dest => dest.Width, opt => opt.MapFrom(src => string.IsNullOrEmpty(src.Width) ? 0 : int.Parse(src.Width)));
方案2:写个通用扩展方法复用逻辑
如果多个地方都需要这种转换,写个扩展方法会更优雅,避免重复代码:
// 先定义扩展方法 public static class StringExtensions { public static int ToIntOrDefault(this string input, int defaultValue = 0) { return int.TryParse(input, out int result) ? result : defaultValue; } } // 然后映射时直接调用 CreateMap<SourceThing, DestinationThing>() .ForMember(dest => dest.Length, opt => opt.MapFrom(src => src.Length.ToIntOrDefault())) .ForMember(dest => dest.Width, opt => opt.MapFrom(src => src.Width.ToIntOrDefault()));
方案3:全局注册类型转换器
要是你整个项目里都需要把字符串转int时处理空值,可以给AutoMapper注册一个全局类型转换器,一劳永逸:
// 自定义转换器 public class StringToIntSafeConverter : ITypeConverter<string, int> { public int Convert(string source, int destination, ResolutionContext context) { return int.TryParse(source, out int result) ? result : 0; } } // 在配置AutoMapper时注册 var mapperConfig = new MapperConfiguration(cfg => { cfg.CreateMap<string, int>().ConvertUsing<StringToIntSafeConverter>(); cfg.CreateMap<SourceThing, DestinationThing>(); }); // 然后初始化mapper var _mapper = mapperConfig.CreateMapper();
方案4:改用可空int(如果业务允许)
如果你的业务逻辑允许DestinationThing的长度/宽度为null,可以把字段类型改成int?(可空int),这样AutoMapper会自动把空字符串转成null,不会报错:
public class DestinationThing { public int? Length; public int? Width; public string Make; }
总之核心就是:AutoMapper默认的类型转换不会处理空字符串这种无效输入,你得自己加逻辑兜底,根据业务需求选上面的方案就行~
内容的提问来源于stack exchange,提问作者Ryan Buening
相关产品推荐
相关产品推荐

