I'm trying to use AutoMapper to convert SourceThing to 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);
The issue I have is when my sourceObj is the following:
{
"Length": "",
"Width": "2",
"Make": "3"
}
I get an error: FormatException: Input string was not in a correct format. AutoMapperMappingException: Error mapping types. Property: Length
Is there something I need to configure to allow AutoMapper to map this successfully?
You need Custom Value Resolvers:
CreateMap<SourceThing, DestinationThing>()
.ForMember(dest => dest.Length,
opt => opt.MapFrom(src => string.IsNullOrWhiteSpace(src.Length)
? default(int)
: int.Parse(src.Length))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With