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

2023-11-24

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

Error:

Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'DateTime'

Entity:

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

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

注:Dto包含DateTime? Deleted too


我还没有测试过,但你应该只需要显式转换null to 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))));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自动映射器映射到可为空的 DateTime 属性 的相关文章

随机推荐