Automapper 映射到可为空的 DateTime 属性

pan*_*mic 3 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 ));
Run Code Online (Sandbox Code Playgroud)

错误:

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; }
}
Run Code Online (Sandbox Code Playgroud)

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

注意:DTO包含DateTime? Deleted太多

ps2*_*oat 6

我还没有测试过,但你应该只需要显式地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))));
Run Code Online (Sandbox Code Playgroud)