自动映射到可以为空的DateTime属性

时间:2018-01-31 21:24:58

标签: c# automapper

使用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 个答案:

答案 0 :(得分: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))));

答案 1 :(得分:1)

只需将新的document.getElementById("thatid").onchange = myFunction(){ /*mycode*/}转换为DateTime

DateTime?