Ryan Buening
Ryan Buening

Reputation: 1660

AutoMapper - Mapping empty string to an int

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?

Upvotes: 3

Views: 2747

Answers (1)

aaron
aaron

Reputation: 43073

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))

Upvotes: 8

Related Questions