1

Closed

Empty string to nullable type conversion using automapper.

description

I have asked this question on stackoverflow
http://stackoverflow.com/questions/19772118/empty-string-to-nullable-type-conversion-using-automapper

I'm trying to convert properties on source object of strings to destination object properties of nullable datatypes(int?,bool?,DateTime?). properties of type string on my source can be empty and when they are empty an equivalent null should be mapped on destination property.It works fine when property has value but when it is empty
It throws an exception {"String was not recognized as a valid Boolean."}
public class SourceTestString
{
  public string IsEmptyString {get; set;}
}

public class DestinationTestBool
{
  public bool? IsEmptyString {get; set;}
}
My Converter class
public class StringToNullableBooleanConverter : ITypeConverter<string,bool?>
 {
     public bool? Convert(ResolutionContext context) 
     {
        if(String.IsNullOrEmpty(System.Convert.ToString(context.SourceValue)) ||  String.IsNullOrWhiteSpace(System.Convert.ToString(context.SourceValue)))
         {
            return default(bool?);
         }
         else
         {
            bool boolValue = false;
            return bool.TryParse(context.SourceValue.ToString(),out boolValue) ?         (bool?)boolValue : default(bool?);
         }
      }
  }
Create Map
AutoMapper.Mapper.CreateMap<string,bool?>().ConvertUsing(new StringToNullableBooleanConverter());
Map Method
SourceTestString source = SourceTestString();
source.IsEmptyString = ""; 
var destination = Mapper.Map<SourceTestString,DestinationTestBool>(source);
Closed May 8, 2014 at 1:19 PM by jbogard

comments

jbogard wrote May 8, 2014 at 1:19 PM

** Closed by jbogard 5/8/2014 6:19 AM

wrote May 8, 2014 at 1:19 PM

wrote May 8, 2014 at 1:19 PM

wrote May 8, 2014 at 1:19 PM