Without looking, I suspect that he called your TypeCoverter
, because it TypeCoverter
best for converted types.
If you create another TypeConverter
with the correct types, it should work fine. For instance:
public class DateTimeConverter : ITypeConverter<DateTime?, DateTime> { public DateTime Convert(ResolutionContext context) { var sourceDate = context.SourceValue as DateTime?; if (sourceDate.HasValue) return sourceDate.Value; else return default(DateTime); } } public class NullableDateTimeConverter : ITypeConverter<DateTime?, DateTime?> { public DateTime? Convert(ResolutionContext context) { var sourceDate = context.SourceValue as DateTime?; if (sourceDate.HasValue) return sourceDate.Value; else return default(DateTime?); } }
Please note that if you want to simplify them to
public class DateTimeConverter : TypeConverter<DateTime?, DateTime> { protected override DateTime ConvertCore(DateTime? source) { if (source.HasValue) return source.Value; else return default(DateTime); } } public class NullableDateTimeConverter : TypeConverter<DateTime?, DateTime?> { protected override DateTime? ConvertCore(DateTime? source) { return source; } }
Then simply initialize both converters:
Mapper.CreateMap<DateTime?, DateTime>().ConvertUsing<DateTimeConverter>(); Mapper.CreateMap<DateTime?, DateTime?>().ConvertUsing<NullableDateTimeConverter>(); Mapper.AssertConfigurationIsValid();
source share