Reputation: 459
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
{
return bool.Parse(context.SourceValue.ToString());
}
}
}
Create Map
AutoMapper.Mapper.CreateMap<string,bool?>().ConvertUsing(new StringToNullableBooleanConverter());
Map Method
SourceTestString source = SourceTestString();
source.IsEmptyString = "";
var destination = Mapper.Map<SourceTestString,DestinationTestBool>(source);
Upvotes: 0
Views: 1912
Reputation: 459
Actually, The Code in my question working perfectly. It was one of my properties which was bool instead of bool? and I apologize for that and thanks for one and all for participation.
Upvotes: 1
Reputation: 32541
Try this:
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=null;
bool evalBool;
if (bool.TryParse(context.SourceValue.ToString(), out evalBool))
{
boolValue = evalBool;
}
return boolValue;
}
}
}
Upvotes: 0