【问题标题】:Automapper map to nullable DateTime propertyAutomapper 映射到可为空的 DateTime 属性
【发布时间】:2018-01-31 21:24:58
【问题描述】:

使用 Automapper 3.1.1 我无法编译此地图:

Mapper.CreateMap<Domain.DomainObjects.Entities.Patient, PatientDto>()
                .ForMember(x => x.Deleted, opt => opt.MapFrom(input => input.Deleted.HasValue ? 
                    new DateTime(input.Deleted.Value.Ticks, DateTimeKind.Utc) : null ));

错误:

Type of conditional expression cannot be determined because there is no implicit conversion between '&lt;null&gt;' and 'DateTime'

实体:

public class Patient : Entity
{
        // more properties
        public virtual DateTime? Deleted { get; set; }
}

感觉好像我遗漏了一些明显的东西,但无法弄清楚到底是什么。

注意:Dto 也包含DateTime? Deleted

【问题讨论】:

    标签: c# automapper


    【解决方案1】:

    我还没有测试过,但您只需要将null 显式转换为DateTime?。 ((DateTime?)null)

    Mapper.CreateMap<Domain.DomainObjects.Entities.Patient, PatientDto>()
                    .ForMember(x => x.Deleted, opt => opt.MapFrom(input => input.Deleted == null ? (DateTime?)null : (
                    new DateTime(input.Deleted.Value.Ticks, DateTimeKind.Utc))));
    

    【讨论】:

      【解决方案2】:

      只需将新的DateTime 转换为DateTime?

      Mapper.CreateMap<Domain.DomainObjects.Entities.Patient, PatientDto>()
                  .ForMember(x => x.Deleted, opt => opt.MapFrom(input => input.Deleted.HasValue ? 
                      (DateTime?) new DateTime(input.Deleted.Value.Ticks, DateTimeKind.Utc) : null ));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-19
        • 2017-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-30
        • 2016-01-22
        相关资源
        最近更新 更多