问题
So I have a source db column with a date where the type is string, not date, so as you would expect there are occasionaly invalid dates such as "10-31-". The source is beyond my control so I can't fix it there (add validation). I'm using automaper (version 9) and I've been trying to use the .MapFrom but to be honest, I'm reasonably new to Automapper and have no real clue as to what I'm doing. I've read over the documentation and it didn't help me.
The destination date column is nullable, so I would like to get a null if the string isn't convertable to a date.
CreateMap<Models.Orders, DTO.Orders>()
.ForMember(dest => dest.ap_birthday, opt => opt.AllowNull() );
回答1:
You can achieve this with a type converter, e.g.:
public class DateTimeTypeConverter : ITypeConverter<string, DateTime?>
{
public DateTime? Convert(string source, DateTime? destination, ResolutionContext context)
{
if (DateTime.TryParse(source, out DateTime result))
return result;
return null;
}
}
This is just an example of a possible type converter. When the string was succesfully parsed, you'll get a DateTime
result, otherwise null
will be returned. Of course you can adjust the conversion to your needs.
You then use the converter like this:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<string, DateTime?>().ConvertUsing(new DateTimeTypeConverter());
cfg.CreateMap<OrderDto, Order>();
});
var mapper = config.CreateMapper();
var orderDTO = new OrderDto();
orderDTO.id = 1;
orderDTO.orderDate = "2020-01-01";
var order = mapper.Map<Order>(orderDTO); // orderDate will be "2020-01-01"
orderDTO.orderDate = "10-31";
var otherorder = mapper.Map<Order>(orderDTO); // orderDate will be null
The line cfg.CreateMap<string, DateTime?>()...
tells AutoMapper to use this converter every time when it needs to convert from string
to DateTime?
.
As an alternative, you can also use a value converter.
来源:https://stackoverflow.com/questions/59672008/how-to-handle-invalid-dates-with-automapper