繁体   English   中英

自动映射器映射到可为null的DateTime属性

[英]Automapper map to nullable DateTime property

使用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 DateTime? Deleted

我尚未测试,但是您只需要显式将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))));

只需将新的DateTimeDateTime?

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 ));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM