如何使用Automapper处理无效日期? [英] How to handle invalid dates with Automapper?

查看:47
本文介绍了如何使用Automapper处理无效日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个源db列,其日期类型为字符串,而不是日期,因此,您可能会偶尔遇到无效的日期,例如"10-31-".该源超出了我的控制范围,因此无法在那里进行修复(添加验证).我使用的是automaper(版本9),并且我一直在尝试使用.MapFrom,但是老实说,我对Automapper相当陌生,对我在做什么并不了解.我已经阅读了文档,但对我没有帮助.

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() );

推荐答案

您可以使用类型转换器,例如:

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;
    }
}

这只是可能的类型转换器的示例.成功解析字符串后,您将获得 DateTime 结果,否则将返回 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

cfg.CreateMap< string,DateTime?>()... 行告诉AutoMapper每次需要从 string 转换为 DateTime?.

The line cfg.CreateMap<string, DateTime?>()... tells AutoMapper to use this converter every time when it needs to convert from string to DateTime?.

或者,您也可以使用值转换器

这篇关于如何使用Automapper处理无效日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆