【问题标题】:Strategy for mapping strings as dates to datetime using Mapster when strings may be empty?当字符串可能为空时,使用 Mapster 将字符串作为日期映射到日期时间的策略?
【发布时间】:2020-05-08 08:59:08
【问题描述】:

我正在使用 Mapster 将值从基于 json 对象的 dto 映射到实体框架数据表。 目标类有一个字段 [Column(TypeName = "datetime2(3)")] public DateTime? CorrectBy { get; set; } 从表示日期的字符串中填充。字符串可以为空或“”。

是否有使用 Mapster 处理此问题的良好映射策略? 我的映射目前如下所示:

TypeAdapterConfig<InModels.Violation, InspectionViolation>.NewConfig()
            .Map(d=>d.CorrectBy,s=>DateTime.Now,srcCond=>srcCond.CorrectBy=="")
            .Map(d => d.CorrectBy, s =>DateTime.Parse(s.CorrectBy))                
            .IgnoreNullValues(true);

但仍然抛出一个错误,说它无法将“”转换为日期时间。

【问题讨论】:

    标签: c# mapster


    【解决方案1】:

    不支持将空字符串转换为DateTime。您需要定义自定义字符串到日期时间的映射。

    TypeAdapterConfig<string, DateTime?>.NewConfig()
        .MapWith(src => string.IsNullOrEmpty(src) ? null : (DateTime?)DateTime.Parse(src));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-11
      • 2013-06-28
      • 2015-09-17
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多