Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper - Mapping empty string to an int

Tags:

c#

automapper

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?

like image 825
Ryan Buening Avatar asked Nov 26 '25 12:11

Ryan Buening


1 Answers

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))
like image 187
aaron Avatar answered Nov 28 '25 01:11

aaron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!