代码之家  ›  专栏  ›  技术社区  ›  pandemic

自动映射到nullable DateTime属性

  •  5
  • pandemic  · 技术社区  · 7 年前

    使用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 '<null>' and 'DateTime'

    实体:

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

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

    注:Dto包含 DateTime? Deleted

    2 回复  |  直到 7 年前
        1
  •  9
  •   ps2goat    7 年前

    我还没有测试,但您应该只需要显式地强制转换 null 到a 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
  •  2
  •   YuvShap    7 年前

    只需投下新的 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 ));