How to handle invalid dates with Automapper?

半世苍凉 提交于 2021-01-28 14:42:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!